Your cart is currently empty!
Code to exclude certain categories from search results in WordPress
When selling paid articles on WordPress, if the search term is included in the paid article, by default the paid article will also be displayed in the search results.
If this happens, the content of the paid article may become known to people other than the purchaser, so I would like to avoid this.
Today I will introduce a code that can be used in such cases.
First, organize paid articles into one category.
Assume that the category of paid articles is 5.
Then, try putting the following code in functions.php.
// Code to exclude certain categories from search results
function mycustom_search_filter_cat_func( $query ) {
if ( $query->is_search() && $query->is_main_query() && ! $query->is_admin() ) {
$cat_id = array( '5' );
$query->set( 'category__not_in', $cat_id );
}
return $query;
}
add_filter( 'pre_get_posts', 'mycustom_search_filter_cat_func' );
If the category ID is divided into two or more, such as 5 and 15, enter them as follows.
// Code to exclude certain categories from search results
function mycustom_search_filter_cat_func( $query ) {
if ( $query->is_search() && $query->is_main_query() && ! $query->is_admin() ) {
$cat_id = array( '5', '15' );
$query->set( 'category__not_in', $cat_id );
}
return $query;
}
add_filter( 'pre_get_posts', 'mycustom_search_filter_cat_func' );
Comments
Featured products
-
[WAV] Hiphop and Rap Music – Genx Beats
$7.00 or more -
[WAV] Hiphop and Rap Music Vol. 2 – Genx Beats
$7.00 or more -
[WAV] Hiphop and Rap Music Vol. 3 – Genx Beats
$7.00 or more
Leave a Reply