Support

Account

Home Forums General Issues Pre_get_posts loop

Solved

Pre_get_posts loop

  • Hi there,

    I want to exclude my search results by post ids.
    Therefor I created an relation field as option.

    But the get_field is probably also using pre_get_posts and gets into an infinite loop.
    This is my code.

    function wpb_search_filter( $query ) {
    
       if(!is_admin() && is_search()){
    
        $excluded_post_ids = get_field('exclude_from_search','option');
    
        if(!empty($excluded_post_ids)){
    
          if ( $query->is_search && !is_admin() ){
            $query->set( 'post__not_in', $excluded_post_ids );
          }
        }
      }
      
      return $query;
    
    }
    add_filter( 'pre_get_posts', 'wpb_search_filter' );

    How do I set the proper IF statement?

    Thanks in advance!

  • try adding a check to see if it is then main query

    
    function wpb_search_filter( $query ) {
    
       if(!is_admin() && is_search() && $query->is_main_query()){
    
        //..... code continues
    
  • Hi John,

    Thanks for the incredibly fast and accurate answer. Problem solved!

    Thanks

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.