Forums › Forums › Search & Filter Pro › Results showing from excluded categories
- This topic has 8 replies, 3 voices, and was last updated 10 years, 5 months ago by Ross.
-
Anonymous(Private) May 22, 2014 at 12:19 pm #818
Hi,
I have excluded 3 categories from my search form. This works in that the excluded categories are not shown on the form, but if I type in a keyword from a post in an excluded category, it still shows up in the search results. Is this correct or is there anything else I can do to stop a post from an excluded category appearing in the search results?
Thank you
Ross Moderator(Private) May 22, 2014 at 12:41 pm #821Hey Ellen
Currently there is no way to define “defaults” for the form to use except for post types..
I do plan on adding this in at some stage, but for now you will have to use
pre_get_posts
hook in order to modify your query (place this in yourfunctions.php
):function exclude_category( $query ) { global $sf_form_data; if ( $sf_form_data->is_valid_form() && $query->is_main_query() ) { $query->set( 'cat', '-2' ); } } add_action( 'pre_get_posts', 'exclude_category' );
You’ll see in there is
$sf_form_data->is_valid_form()
– this tells us we are on a S&F search form so to only modify the query then.This statement will affect all search & Filter forms however, so if you are using more than one form on your site you will need some more conditional statements.. let me know if this is the case?
Thanks
Anonymous(Private) May 22, 2014 at 1:10 pm #823Many thanks – I’ll try that. I do only have one S&F form. Actually I would quite like to exclude the 3 categories from the WordPress search as well if that were possible – should I omit the
$sf_form_data->is_valid_form()
bit for that? No problem if that’s not possible though.Ross Moderator(Private) May 22, 2014 at 1:28 pm #825Hey Ellen
To exclude categories by ID you need to list them (sorry I wasn’t clearer) here:
$query->set( 'cat', '-2' );
This removes categories with the id of
2
. The minus number means “exclude”. If you want multiple categories then comma separate them:$query->set( 'cat', '-1,-23,-8' );
And yeah to make the categories disappear from all main queries then remove that line. There was one problem with my example actually – I needed to add an
is_admin
check – so the full code for you would be something like:function exclude_category( $query ) { global $sf_form_data; //if ( $query->is_main_query() && !is_admin() ) - use this line instead to exclude cats from all queries if ( $sf_form_data->is_valid_form() && $query->is_main_query() && !is_admin() ) { $query->set( 'cat', '-2,-4,-10,-6' ); } } add_action( 'pre_get_posts', 'exclude_category' );
Hope that helps!
Ross Moderator(Private) July 21, 2014 at 1:37 pm #2707Hey Joe
I’m going to have to do some tests… Can you open a new ticket for this?
Thanks
-
AuthorPosts