class-wp-sitemaps-index.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * Sitemaps: WP_Sitemaps_Index class.
  4. *
  5. * Generates the sitemap index.
  6. *
  7. * @package WordPress
  8. * @subpackage Sitemaps
  9. * @since 5.5.0
  10. */
  11. /**
  12. * Class WP_Sitemaps_Index.
  13. * Builds the sitemap index page that lists the links to all of the sitemaps.
  14. *
  15. * @since 5.5.0
  16. */
  17. #[AllowDynamicProperties]
  18. class WP_Sitemaps_Index {
  19. /**
  20. * The main registry of supported sitemaps.
  21. *
  22. * @since 5.5.0
  23. * @var WP_Sitemaps_Registry
  24. */
  25. protected $registry;
  26. /**
  27. * Maximum number of sitemaps to include in an index.
  28. *
  29. * @since 5.5.0
  30. *
  31. * @var int Maximum number of sitemaps.
  32. */
  33. private $max_sitemaps = 50000;
  34. /**
  35. * WP_Sitemaps_Index constructor.
  36. *
  37. * @since 5.5.0
  38. *
  39. * @param WP_Sitemaps_Registry $registry Sitemap provider registry.
  40. */
  41. public function __construct( WP_Sitemaps_Registry $registry ) {
  42. $this->registry = $registry;
  43. }
  44. /**
  45. * Gets a sitemap list for the index.
  46. *
  47. * @since 5.5.0
  48. *
  49. * @return array[] Array of all sitemaps.
  50. */
  51. public function get_sitemap_list() {
  52. $sitemaps = array();
  53. $providers = $this->registry->get_providers();
  54. /* @var WP_Sitemaps_Provider $provider */
  55. foreach ( $providers as $name => $provider ) {
  56. $sitemap_entries = $provider->get_sitemap_entries();
  57. // Prevent issues with array_push and empty arrays on PHP < 7.3.
  58. if ( ! $sitemap_entries ) {
  59. continue;
  60. }
  61. // Using array_push is more efficient than array_merge in a loop.
  62. array_push( $sitemaps, ...$sitemap_entries );
  63. if ( count( $sitemaps ) >= $this->max_sitemaps ) {
  64. break;
  65. }
  66. }
  67. return array_slice( $sitemaps, 0, $this->max_sitemaps, true );
  68. }
  69. /**
  70. * Builds the URL for the sitemap index.
  71. *
  72. * @since 5.5.0
  73. *
  74. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  75. *
  76. * @return string The sitemap index URL.
  77. */
  78. public function get_index_url() {
  79. global $wp_rewrite;
  80. if ( ! $wp_rewrite->using_permalinks() ) {
  81. return home_url( '/?sitemap=index' );
  82. }
  83. return home_url( '/wp-sitemap.xml' );
  84. }
  85. }