For me, one of the most irritating features of 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 https://yoa.st 🙂

Sitemaps are XML files. However, any XML file can be rendered to 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.

However, 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="//wildwolf.name/wp-content/plugins/wordpress-seo/css/main-sitemap.xsl"?>

We need to modify the value of the href attribute to reference an existing static file or register a “virtual” XML stylesheet and serve its content dynamically.

Whichever way we prefer, the first step is 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, 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 the init action into the $wpseo_sitemaps variable. To register a custom stylesheet, WPSEO_Sitemaps provides the register_xsl() method. Its first argument is the name of the stylesheet (the part before -sitemap.xsl). 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"?>
...
EOF;
}

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 *