Creating a custom sitemap with pagination for Rank Math SEO plugin is a powerful feature for SEO optimization. With a custom sitemap, you can control how your content is organized and indexed by search engines. In this article, we will explore how to create a custom sitemap using Rank Math SEO and add pagination to it.

History: The Need for a Custom Sitemap

As you may already know, search engines like Google, Bing, and others rely on sitemaps to understand the structure and content of a website. These sitemaps serve as a roadmap, guiding search engine bots through the intricate web of your site’s pages and content. Typically, sitemaps are automatically generated by SEO plugins like Rank Math. However, here’s where our journey takes an interesting turn.

The default Rank Math sitemap, while a valuable tool for most websites, faced a monumental challenge when dealing with a directory site of this magnitude. You see, there’s a limitation when it comes to sitemaps: they are limited to 50,000 URLs per sitemap. While this is usually more than enough for most websites, it’s a mere fraction of what was needed for a directory site with 90 million records.

In practice, this limitation meant that the default Rank Math sitemap encountered significant roadblocks. It struggled to handle the long list of URLs that needed to be included, and this struggle resulted in white screen errors, effectively rendering the sitemap unusable. A solution was urgently needed to overcome this obstacle and make it possible for the directory website to effectively communicate with search engines. And so, the solution was born out of necessity. The strategy involved bypassing the default sitemap generation process and devising a direct SQL query to fetch the results from the database. But the journey didn’t end there. To work within the confines of the 50,000 URL limitation, a custom sitemap had to be created with pagination, ensuring that the directory’s vast database of information could be neatly organized into digestible portions for search engines to consume.

The creation of this custom sitemap marked a pivotal moment in optimizing the indexing of the directory website’s content. It not only solved the technical challenges posed by the site’s immense size but also showcased the adaptability and innovation of SEO experts in navigating the ever-changing landscape of digital marketing.

Step 1: Introduction

Before we dive into the code, let’s briefly understand what we’re trying to achieve. We want to create a custom sitemap for a custom post type called “publicdevs.” This sitemap will be divided into multiple pages with pagination, allowing search engines to index all the content efficiently.

Step 2: Register the Sitemap Provider

The first step is to register your custom sitemap provider. You will do this in your theme’s functions.php file. This provider will be responsible for generating the sitemap for your “publicdevs” post type.

// functions.php
add_filter('rank_math/sitemap/providers', function($external_providers) {
    $external_providers['publicdevs'] = new \RankMath\Sitemap\Providers\PD_Sitemap();
    return $external_providers;
});

In the code above, we are using the add_filter function to hook into the rank_math/sitemap/providers filter and add our custom sitemap provider, which is an instance of the PD_Sitemap class.

As, we have create separate file, you also need to include this in your theme:

require_once "inc/pd-sitemap.php";

Step 3: Create the Sitemap Provider

Next, you need to create the PD_Sitemap class, which implements the Provider interface. This class will handle the generation of the sitemap.

<?php
namespace RankMath\Sitemap\Providers;

use RankMath\Sitemap\Router;

class PD_Sitemap implements Provider {

    // Your code here...

}

In the PD_Sitemap class, you will implement several methods that define how your custom sitemap will work. Let’s break down the key methods:

1. total_ps_count():

This method calculates the total number of “publicdevs” posts that need to be included in the sitemap.

public function total_ps_count() {
    global $wpdb;
    return (int) $wpdb->get_var("SELECT COUNT({$wpdb->posts}.ID) FROM {$wpdb->posts} WHERE post_type = 'publicdevs' AND post_status = 'publish'");
}

2. handles_type($type):

This method checks if the sitemap provider should handle a particular post type. In this case, it checks if the post type is “publicdevs.”

public function handles_type( $type ) {
    return 'publicdevs' === $type;
}

3. get_index_links($max_entries):

This method generates the index links for your sitemap, including pagination. It calculates the number of pages needed and creates links to those pages. The last modified date is set for all index links.

public function get_index_links( $max_entries ) {
    $index = [];
    $total_count = $this->total_ps_count();

    $max_pages = 1;
    if ( $total_count > $max_entries ) {
        $max_pages = (int) ceil( $total_count / $max_entries );
    }

    for ( $page_counter = 0; $page_counter < $max_pages; $page_counter++ ) {
        $current_page = ( $max_pages > 1 ) ? ( $page_counter + 1 ) : '';
        $index[] = [
            'loc'     => Router::get_base_url( 'pd-sitemap' . $current_page . '.xml' ),
            'lastmod' => '2023-05-03 05:33 +00:00'
        ];
    }

    return $index;
}

4. get_sitemap_links($type, $max_entries, $current_page):

This method generates the actual sitemap links. It retrieves the necessary data for your “publicdevs” posts and formats the links accordingly. Pagination is applied here, limiting the number of links on each page.

public function get_sitemap_links( $type, $max_entries, $current_page ) {
    global $wpdb;

    $links     = [];

    $results = $wpdb->get_results(
        "SELECT P.post_name, P.post_date, P.post_modified, T.slug FROM `wp_posts` AS P INNER JOIN `wp_term_relationships` AS TR ON P.ID = TR.object_id INNER JOIN `wp_term_taxonomy` AS TT ON TT.term_taxonomy_id = TR.term_taxonomy_id INNER JOIN `wp_terms` AS T ON T.term_id = TT.term_id WHERE P.post_type = 'publicdevs' AND P.post_status = 'publish' AND TT.taxonomy = 'state' ORDER BY P.ID DESC",
        ARRAY_A
    );

    foreach($results as $single_res) {
        $link = sprintf(
            'https://yourwebsite.com/%s/%s/',
            $single_res['slug'],
            $single_res['post_name']
        );
        $datetime = isset($single_res['post_modified']) ? $single_res['post_modified'] : $single_res['post_date'];
        $links[] = [
            'loc' => $link,
            'mod' => sprintf('%s', $datetime)
        ];
    }

    $links = array_slice(
        $links,
        (($current_page - 1) * $max_entries),
        $max_entries
    );

    return $links;
}

Step 4: Configure Your Sitemap in Rank Math

After creating the custom sitemap provider, you need to configure it in the Rank Math plugin settings.

  1. In your WordPress dashboard, go to “Rank Math” and click on “Sitemap Settings.”
  2. You should see a section for “publicdevs” (or your custom post type). Make sure it’s enabled.
  3. Save your settings.

Step 5: Verify Your Sitemap

To make sure everything is working as expected, you can view your custom sitemap in a web browser by navigating to the following URL:

https://yourwebsite.com/sitemap_index.xml

Replace “yourwebsite.com” with your actual website domain. You should see your custom sitemap with pagination links.

Conclusion

Creating a custom sitemap with pagination in Rank Math SEO is a valuable tool for optimizing the indexing of your content. By implementing a custom sitemap provider and configuring it in Rank Math, you can have better control over how your “publicdevs” posts are indexed and organized. This can lead to improved SEO and better visibility in search engine results.

Categorized in:

WordPress,

Tagged in:

,