How to Exclude Products from a Specific WooCommerce Product Category in Yoast's Sitemap

By Gordon Smith

Yoast makes generating XML sitemaps for SEO really easy. But sometimes we want to generate a sitemap of WooCommerce products which exclude one or more specific product categories. Fortunately this can be achieved using Yoast's built-in hooks and a call to a WooCommerce to get all the products in a specific category. 

Add the following code into the functions.php file of your WordPress theme, or inject it using a WordPress code injection plugin. You'll need to modify the "spare-part" slug to the slug of the product category you want to exclude. 

Sample code:

 

/* Dotwise - code to exclude all products in spare parts category from XML sitemaps: */
/* Reference: https://developer.yoast.com/features/xml-sitemaps/api/ /*

/**
 * Excludes posts from XML sitemaps.
 *
 * @return array The IDs of posts to exclude.
 */
function dotwise_exclude_posts_from_xml_sitemaps()
{
    WC();
    $category = 'spare-part';
    $args = array(
        'category' => $category, // slug of the category we want to remove from the sitemap
        'limit' => 100, // upper limit of number of products to exclude if needed. Note: use -1 for unlimited or omit altogether to return the default number of products in a page for your website.
        'return' => 'ids', // we only want the ID numbers of the products, not the whole product object for this purpose
    );

    $query = new WC_Product_Query($args);
    $products = $query->get_products(); // get the product IDs

    return $products; // return the list of product IDs to exclude
}

add_filter('wpseo_exclude_from_sitemap_by_post_ids', 'dotwise_exclude_posts_from_xml_sitemaps');

Products in a category

Products in a category