1

I have a search bar on 2 pages in my site and on my page called archive I want to exclude a category called economics (id - 9) from the search. I have placed this in my functions.php file:

function archive_search_filter( $query ) {
  if ( $query->is_search && $query->is_main_query() ) {
  $query->set( 'category__not_in' , '9' );
  }
}
add_filter( 'pre_get_posts', 'archive_search_filter' );

and it works perfectly but I want to only have this implemented on the page called archive. If I try an if statement with is_page('archive') along with this it is not working and I'm not sure of a solution. I'm wondering if the functions.php loads before it can tell what page it is and if there is another way to get this to work.

  • Did you mean page archive or the post archive? – obiPlabon Feb 21 '18 at 14:51
  • it's just a page called archive, it isn't either of those – jessica mele Feb 21 '18 at 14:56
1

The problem is that pre_get_posts is called after you leave the page, so you must also test to see if the search was done from there and for that you can use wp_get_referer()

So (in theory, sorry I haven't the time to test this) you could have

if ( !is_admin() && $query->is_search() && $query->is_main_query() && wp_get_referer() == "http://www.example.com/archive" ) {

Hope that helps

PS: Always add a !is_admin() check to make double-sure you're not effecting admin queries... belt & braces!

  • thanks Peter this worked for me and thanks for the tip about !is_admin() – jessica mele Feb 21 '18 at 17:54
1

Please try the following code.

function archive_search_filter( $query ) {
    if ( ! is_admin() && is_page( 'archive' ) ) {
        $query->set( 'category__not_in' , '9' );
    }
}
add_filter( 'pre_get_posts', 'archive_search_filter' );
  • thanks but no luck with that either – jessica mele Feb 21 '18 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.