Newbie question: exclude category from search?

[ad_1]

Yes it does. I find it much easier to prevent things from being indexed than I do to prevent from being part of the considered results, thus why I have taken this route below.

function wpswa_support_should_index_post( $should_index, $post ) {
	// Get WP_Term objects for the categories on the post
	$categories = get_the_category( $post->ID );
	
	// Get just the slugs as an array
	$category_slugs = wp_list_pluck( $categories, 'slug' );

	// Check if "meat" is in the list of slugs, if yes, return false to prevent indexing.
	if ( in_array( 'meat', $category_slugs, true ) ) {
		return false;
	}

	// Otherwise return our original value
	return $should_index;
}
add_filter( 'algolia_should_index_post', 'wpswa_support_should_index_post', 10, 2 );
add_filter( 'algolia_should_index_searchable_post', 'wpswa_support_should_index_post', 10, 2 );

We make use of our “should index” filters, which allows for filtering whether or not a given post should be indexed.

With this code, we grab the categories for the given post being considered, and then fetch just the slugs for the categories. We then check if “meat” is in the array of slugs. If yes, return false, to prevent indexing. Otherwise we return the original value.

This should go in your active theme’s functions.php or perhaps a quick custom plugin/must use plugin.

Hopefully this makes enough logical sense to adapt as needed, for example if the slug isn’t “meat” exactly, you could match it up to the slug you have.

You’ll want to either quick edit/save each post that has “meat” on it, after saving the code, or run a bulk re-index to get the items removed from the index. Saving the code alone won’t automatically update your Algolia index.

Let me know if you have any other questions.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer