One thing I do not like about Yoast SEO is that it is pretty aggressive in its advertising attempts, and it seems like there is no way to stop it from putting links back to its site. In my opinion, this violates the Guideline #10 of the WordPress Plugin Handbook, but that is just my opinion.

If you open a sitemap or sitemap index in a browser, you will see something like this:

“Yoast” and “SEO” are two backlinks to 🙂

Sitemaps are XML files, but any XML file can be rendered as an HTML with the help of an XML Stylesheet. Yoast SEO uses its own stylesheet for that, and provides no way (via the administrative interface) to use a custom one.

Yoast SEO provides a filter named wpseo_stylesheet_url, which allows for modification of the <?xml-stylesheet?> processing instruction. The instruction itself looks like this:

<?xml-stylesheet type="text/xsl" href="//"?>

We need to modify the value of the href attribute so that it either references an existing static file, or register a “virtual” XML stylesheet and serve its content dynamically.

Whichever way we prefer, the first step will be the same:

function my_wpseo_stylesheet_url($s)
    return str_replace('/wp-content/plugins/wordpress-seo/css/main-sitemap.xsl', '/my-sitemap.xsl', $s);

add_filter('wpseo_stylesheet_url', 'my_wpseo_stylesheet_url');

If my-sitemap.xsl is a static file, then we do not need to do anything else. If we want to generate the content dynamically, we need to add more code.

WPSEO_Sitemaps class manages sitemaps. It is instantiated during init action into $wpseo_sitemaps variable. To register a custom stylesheet, WPSEO_Sitemaps provides register_xsl() method: its first argument is the name of the stylesheet (the part before -sitemap.xsl), and the second argument is the callable which dynamically generates the stylesheet.

function my_stylesheet()
    header('Content-Type: text/xsl; charset=utf-8');
    header('X-Robots-Tag: noindex, follow', true);
    echo <<<EOF
<?xml version="1.0" encoding="UTF-8"?>

function my_init()
    global $wpseo_sitemaps;
    if (class_exists('WPSEO_Sitemaps', false) && $wpseo_sitemaps instanceof WPSEO_Sitemaps) {
        $wpseo_sitemaps->register_xsl('my', 'my_stylesheet');

add_action('init', 'my_init', /* Make sure it runs after Yoast SEO's init */ 11);

That’s it 🙂

Yoast SEO: How to Use a Custom Stylesheet for Sitemaps
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *