• Resolved fabiopwl37

    (@fabiopwl37)


    I need to hide out of stock products that belong to a specific category from search results. I have tried multiple variations of the example below but none seem to have an effect. Here is what I am currently trying:

    In functions.php,

    function my_search_func($q){
    	
    	if (!$q->is_admin() && $q->is_search() && $q->is_main_query()){
    		if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) {
    			$tax_query = (array) $q->get('tax_query');
    	 
    			$q->set( 'tax_query', array(
    				 'relation' => 'AND',
    				  array(
    					'taxonomy' => 'product_visibility',
    					'field' => 'term_taxonomy_id',
    					'terms' => array( $outofstock_term->term_taxonomy_id ),
    					'operator' => 'NOT IN'
    				  ),
    				  array(
    					'taxonomy' => 'product_cat',
    					'field'    => 'slug',
    					'terms'    => 'my-category-slug',
    					'operator' => 'NOT IN',
    				  ),
    			));
    	 
    		}
    		remove_action( 'pre_get_posts', 'my_search_func' );
    	}
    	
    }
    add_action( 'pre_get_posts', 'my_search_func' );

    Is there a different hook for the plugin perhaps? I am using a similar function to hide the out of stock products on the specific category page and it is working well.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author YummyWP

    (@yummy-wp)

    Hello,

    It’s not possible to change the search query for results in the popup. That action may work for search results page, but you need to add a priority 99999
    add_action( 'pre_get_posts', 'my_search_func', 99999 );

    Also you can filter results in the popup :

    
    function filter_search_results( $posts ){
        $filtered_posts = [];
        foreach ($posts as $p) {
            if (...) {
                $filtered_posts[ $p->ID ] = $p;
            }
        }
        return $filtered_posts;
    
    }
    add_action( 'smart_search_query_results', 'filter_search_results' );
    
    Thread Starter fabiopwl37

    (@fabiopwl37)

    The result filter worked like a charm, thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom tax_query not working for search results’ is closed to new replies.