[wd_asp elements=’search’ ratio=’100%’ id=1]

Exclude category from blog while adding them to sitemap.xml

16th January 2024

Wordpress - Miscellaneous

wordpress category

Add to functions.php page

Excludes category 74 from the wordpress blog page, then adds all in cat 1 and 74 to the sitemap.


// Exclude 'locations' category from the blog page
function exclude_category_from_blog($query) {
if ($query->is_home()) {
$query->set('cat', '-74'); // Excludes posts from category ID 74
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category_from_blog');

// Manually add 'locations' and 'General' category posts to the sitemap
function add_specific_categories_to_sitemap($args) {
if (!isset($args['tax_query'])) {
$args['tax_query'] = array();
}

// Prepare the tax query for both 'locations' and 'General' categories
$locations_general_tax_query = array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => 74, // ID of the 'locations' category
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => 1, // ID of the 'General' category
),
);

// If there is an existing tax query, merge it with the new one
if (!empty($args['tax_query'])) {
$args['tax_query'] = array_merge($args['tax_query'], $locations_general_tax_query);
} else {
$args['tax_query'] = $locations_general_tax_query;
}

return $args;
}
add_filter('wp_sitemaps_posts_query_args', 'add_specific_categories_to_sitemap');