Add custom URLs to WordPress’s XML sitemap

Sitemap Provider

It’s possible to create a so called custom sitemap provider and register it with wp_register_sitemap_provider().

It’s helpful to look at the core setup, e.g. for the WP_Sitemaps_Posts provider and also the dev notes.

Basic Example – Sitemap with custom URLs

Here’s a very basic example that adds the wpse provider that extends WP_Sitemaps_Provider, through an anonymous class:

add_action ( 'init', function () {  
    wp_register_sitemap_provider( 
        'wpse', 
        new class extends \WP_Sitemaps_Provider {
            public function __construct() {
                $this->name="wpse"; // public-facing name in URLs says parent class.
            }
            public function get_url_list( $page_num, $post_type="" ) {
                return array(
                    array(
                        'loc' => add_query_arg( 'x', 1, home_url() ),
                    ),
                    array(
                        'loc' => add_query_arg( 'x', 2, home_url() ),
                    ),
                );
            }
            public function get_max_num_pages( $subtype="" ) {
                return 1;
            }
        }
    );
} );

It will generate wp-sitemap-wpse-{PAGE NUMBER <= get_max_num_pages()}.xml or wp-sitemap-wpse-1.xml:

enter image description here

that contains these two custom urls:

enter image description here

External DB

For an external DB you can adjust the get_max_num_pages() and get_url_list() methods above, with the help of e.g.:

  • overall number of x values from the external DB
  • paginated chunk of x values from the external DB
  • wp_sitemaps_get_max_urls() that’s 2000 by default
  • current page number $page_num

ps: looking around there is a great article on wp-kama that will probably help a lot regarding the external DB.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)