Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I dynamically exclude post types based on their categories
    WordPress SEO


How can I dynamically exclude post types based on their categories


To dynamically exclude post types based on their categories, you can use the `wpseo_sitemap_entry` filter and check if the post type belongs to a specific category. Here's an example of how you can do it:

php
function exclude_post_types_by_category( $url, $type, $post ) {
    // Define the categories to exclude
    $categories_to_exclude = array( 1, 2, 3 );

    // Get the post categories
    $post_categories = wp_get_post_categories( $post->ID );

    // Check if the post type belongs to any of the excluded categories
    foreach ( $post_categories as $category ) {
        if ( in_array( $category, $categories_to_exclude ) ) {
            // Return false to exclude the post type from the sitemap
            return false;
        }
    }

    // Return the original URL to include the post in the sitemap
    return $url;
}

add_filter( 'wpseo_sitemap_entry', 'exclude_post_types_by_category', 10, 3 );

In this example, the `exclude_post_types_by_category` function checks if the post type belongs to any of the categories specified in the `$categories_to_exclude` array. If it does, the function returns `false`, which tells Yoast SEO to exclude the post type from the sitemap.

You can customize the `$categories_to_exclude` array to include the specific categories you want to exclude.

Citations:
[1] https://wordpress.stackexchange.com/questions/243476/exclude-custom-post-type-in-sitemap-generation
[2] https://www.binarycarpenter.com/how-to-exclude-custom-post-types-posts-pages-from-yoast-seo-sitemap/
[3] https://clicknathan.com/web-design/ocho_no_individual_testimonials_in_sitemap/
[4] https://stackoverflow.com/questions/44530358/wordpress-yoast-exclude-posts-from-xml-sitemap
[5] https://developer.yoast.com/customization/yoast-seo/filters/cornerstone-post-types-filter/