How to Programmatically Exclude Posts from the Yoast SEO for WordPress Plugin

I’m not the biggest fan of Yoast, having created my own setup via some custom code and Advanced Custom Fields to make SEO easy, and non-distracting, however I do realize that a lot of people like it, use it and/or are convinced their website will fail without it.

Today I’m here to talk a little bit about how to work with a filter Yoast provides by the name of wpseo_exclude_from_sitemap_by_post_ids. This much discussed, but poorly documented, feature, is pretty nifty if you’re a developer. For example, say you want to exclude all posts from a specific category.

To do this, use this code:

// Remove posts from a specific category from the Yoast Site Map
function ocho_no_individual_testimonials_in_sitemap() {
$args = array(
'posts_per_page' => -1, // this says, "Get all applicable posts"
'cat' => 37, // this says, "Use the category with the ID of 37"
'post_type' => 'post' // this says, "Use the Post, ie blog post, post type, though this is the default here
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$exclude_array = array(); // create an array of IDs from these posts
while ( $the_query->have_posts() ) {
$this_testimonial_array = get_the_ID(); // get the queried post's ID
$exclude_array[] = $this_testimonial_array; // add the post ID to the array
return $exclude_array; // return our array of IDs in category 37
add_filter( 'wpseo_exclude_from_sitemap_by_post_ids', 'ocho_no_individual_testimonials_in_sitemap');

There you have it!

If you’re not sure where to get the ID of a category, in WordPress go to Posts > Categories and then click on View on the category you’re looking for. Now look in the address bar of your browser, you’ll see something like this, with the category’s ID highlighted in yellow:

Up Next: How to Get Pinterest OpenGraph Info onto Your WordPress Site (Including for Woocommerce!)