WPSEO_Sitemaps_Router

Rewrite setup and handling for sitemaps functionality.

Defined (1)

The class is defined in the following location(s).

/inc/sitemaps/class-sitemaps-router.php  
  1. class WPSEO_Sitemaps_Router { 
  2.  
  3. /** 
  4. * Sets up init logic. 
  5. */ 
  6. public function __construct() { 
  7.  
  8. add_action( 'init', array( $this, 'init' ), 1 ); 
  9. add_filter( 'redirect_canonical', array( $this, 'redirect_canonical' ) ); 
  10. add_action( 'template_redirect', array( $this, 'template_redirect' ), 0 ); 
  11.  
  12. /** 
  13. * Sets up rewrite rules. 
  14. */ 
  15. public function init() { 
  16.  
  17. global $wp; 
  18.  
  19. $wp->add_query_var( 'sitemap' ); 
  20. $wp->add_query_var( 'sitemap_n' ); 
  21. $wp->add_query_var( 'xsl' ); 
  22.  
  23. add_rewrite_rule( 'sitemap_index\.xml$', 'index.php?sitemap=1', 'top' ); 
  24. add_rewrite_rule( '([^/]+?)-sitemap([0-9]+)?\.xml$', 'index.php?sitemap=$matches[1]&sitemap_n=$matches[2]', 'top' ); 
  25. add_rewrite_rule( '([a-z]+)?-?sitemap\.xsl$', 'index.php?xsl=$matches[1]', 'top' ); 
  26.  
  27. /** 
  28. * Stop trailing slashes on sitemap.xml URLs. 
  29. * @param string $redirect The redirect URL currently determined. 
  30. * @return bool|string $redirect 
  31. */ 
  32. public function redirect_canonical( $redirect ) { 
  33.  
  34. if ( get_query_var( 'sitemap' ) || get_query_var( 'xsl' ) ) { 
  35. return false; 
  36.  
  37. return $redirect; 
  38.  
  39. /** 
  40. * Redirects sitemap.xml to sitemap_index.xml. 
  41. */ 
  42. public function template_redirect() { 
  43.  
  44. global $wp_query; 
  45.  
  46. $current_url = 'http://'; 
  47.  
  48. if ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ) { 
  49. $current_url = 'https://'; 
  50.  
  51. $current_url .= sanitize_text_field( $_SERVER['SERVER_NAME'] ); 
  52. $current_url .= sanitize_text_field( $_SERVER['REQUEST_URI'] ); 
  53.  
  54. if ( home_url( '/sitemap.xml' ) === $current_url && $wp_query->is_404 ) { 
  55. wp_redirect( home_url( '/sitemap_index.xml' ), 301 ); 
  56. exit; 
  57.  
  58. /** 
  59. * Create base URL for the sitemap. 
  60. * @param string $page Page to append to the base URL. 
  61. * @return string base URL (incl page) 
  62. */ 
  63. public static function get_base_url( $page ) { 
  64.  
  65. global $wp_rewrite; 
  66.  
  67. $base = $wp_rewrite->using_index_permalinks() ? 'index.php/' : '/'; 
  68.  
  69. /** 
  70. * Filter the base URL of the sitemaps 
  71. * @param string $base The string that should be added to home_url() to make the full base URL. 
  72. */ 
  73. $base = apply_filters( 'wpseo_sitemaps_base_url', $base ); 
  74.  
  75. // Get the scheme from the configured home url instead of letting WordPress determine the scheme based on the requested URI. 
  76. return home_url( $base . $page, parse_url( get_option( 'home' ), PHP_URL_SCHEME ) );