/inc/sitemaps/class-sitemaps-router.php

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