Omit custom post type from wp-sitemap.xml based on meta key using wp_sitemaps_posts_query_args

I'm trying to omit specific CPTs from the WordPress generated wp-sitemap.xml based on a meta key value. I only found one post online regarding this on perishable press, however it throws up a fatal error in PHP whether or not I modify it.

If anyone knows how to do this for meta key values or multiple meta key values using relation, I would appreciate some info. Last piece I need to finalize my sitemaps.

Original code from Perishable Press (throws error)

function shapeSpace_disable_sitemap_post_meta($args, $post_type) {
    
    if ('post' !== $post_type) return $args; // can be any post type
    
    $args['meta_query'] = isset($args['meta_query']) ? $args['meta_query'] : array();  
      
    $args['meta_query'][] = array(
        
        'key'     = 'sitemap', // can be any meta key
        'value'   = '1',       // can be any meta value
        'compare' = '=',       // can use any comparison
    );
    
    return $args;
    
}
add_filter('wp_sitemaps_posts_query_args', 'shapeSpace_disable_sitemap_post_meta');

Modified Code (also throws error)

function shapeSpace_disable_sitemap_post_meta($args, $post_type) {
    
    if ($post_type !== 'authors') return $args; // can be any post type
    
    $args['meta_query'] = isset($args['meta_query']) ? $args['meta_query'] : array();  
      
    $args['meta_query'][] = array(
        
            'key'     = 'doss_enabled', // can be any meta key
            'value'   = '1',       // can be any meta value
            'compare' = '=',       // can use any comparison
        );
    
    return $args;
    
}
add_filter('wp_sitemaps_posts_query_args', 'shapeSpace_disable_sitemap_post_meta');

PHP Error Log

PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function shapeSpace_disable_sitemap_post_meta(), 1 passed in class-wp-hook.php on line 305 and exactly 2 expected in functions.php:92

Topic meta-query sitemap functions php hooks Wordpress

Category Web


The error happens because the filter callback (shapeSpace_disable_sitemap_post_meta()) expects to receive two parameters ($args and $post_type) and yet you call add_filter() without setting the fourth parameter to 2.

So to solve the problem:

// Replace this:
add_filter('wp_sitemaps_posts_query_args', 'shapeSpace_disable_sitemap_post_meta');

// with this one:
add_filter('wp_sitemaps_posts_query_args', 'shapeSpace_disable_sitemap_post_meta', 10, 2);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.