I used this trick several years ago, and I was surprised that sitemap generation plugins still do not use it.

I tried these plugins:

Of all those plugins, Yoast SEO is the only one that implements this feature.

I must say that this trick won’t make sitemap generation drastically faster; it will just reduce the load on your site a bit. If your favorite plugin does not implement it, there is probably nothing to worry about 🙂

Sitemap generation plugins often use the template_redirect hook to display the sitemap (like this). However, lots of things happen before that action fires: muplugins_loaded, plugins_loaded, setup_theme, after_setup_theme, init, widgets_init (fires during the init action), wp_loaded, parse_request, send_headers, parse_query, pre_get_posts, wp, template_redirect. And, this list is not exhaustive.

When we are going to display the sitemap (and sitemaps are XML files), we clearly don’t need widgets.

add_action( 'plugins_loaded', 'my_plugins_loaded' );

function my_plugins_loaded() {
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- we only need raw 4 last characters of the REQUEST_URI, no need to waste time sanitizing the string
    $request_uri = (string) ( $_SERVER['REQUEST_URI'] ?? '' );
    $extension   = strtolower( substr( $request_uri, -4 ) );

    if ( in_array( $extension, [ '.xml', '.xsl' ], true ) && false !== stripos( $request_uri, 'sitemap' ) ) {
        add_action( 'after_setup_theme', 'my_after_setup_theme', PHP_INT_MAX );
    }
}

function my_after_setup_theme() {
    remove_all_actions( 'widgets_init' );
}

What this code does is checks whether the current request is for an XML file (the last four characters of the path are .xml or .xsl), and the request path contains the word “sitemap.” If so, it registers a handler for the after_setup_theme action and removes all registered handlers for the widgets_init hook. We use the after_setup_theme hook instead of plugins_loaded because the theme can choose to install its own widgets, and we need to remove them as well.

How to Improve Performance of Sitemap Generation in WordPress
Tagged on:         

Leave a Reply

Your email address will not be published.