Search code examples
phpwordpresswoocommercehook-woocommercewoocommerce-theming

Custom WooCommerce Product Query is not working


I'm trying to create this custom product query, to only display products on the /shop page with the following tax_query. But it doesn't work.

I've also tried the woocommerce_product_query hook.

Grateful for any suggestions!

add_action( 'pre_get_posts', 'show_active_lotteries_only' );
function show_active_lotteries_only( $q ){ 
    $q->set( 'tax_query', array (
        array(
          'fields' => 'ids',
    'post_type'=> 'product',
    'show_past_lottery' => FALSE,   
    'tax_query' => array(array('taxonomy' => 'product_type' , 'field' => 'slug', 'terms' => 'lottery')),
        )
      ));
}

The query is taken from the lottery plugin documentation (the product being used in the store):

// Return active lottery products.
$args = array(
    'fields' => 'ids',
    'post_type'=> 'product',
    'show_past_lottery' => FALSE,   
    'tax_query' => array(array('taxonomy' => 'product_type' , 'field' => 'slug', 'terms' => 'lottery')),    
);   

Solution

  • So for your conditional check whether you're on the shop page or not you could use the following woocommerce function:

    // This will make sure that you're on the shop page
    is_shop();
    

    Also for writing your tax_query you could assign all of the arrays/filters to a variable like so:

    $tax_query = array(
      // If you have multiple filters/arrays then
      // You could also assign a relationship to these filters
      // 'relation' => 'AND'/'OR'
      array(
        'taxonomy' => 'product_type',
        'field'    => 'slug',
        'terms'    => 'lottery'
      ),
      // Another array/filter
      // array(
      // ...YOUR ARGs HERE...
      // )
    );
    

    So the final code would be something like this:

    add_action('pre_get_posts', 'show_active_lotteries_only');
    
    function show_active_lotteries_only($q)
    {
      if (is_shop()) {
        $tax_query = array(
          array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => 'lottery'
          )
        );
        $q->set('tax_query', $tax_query);
        $q->set('post_type', 'product');
        $q->set('post_status', 'publish');
        $q->set('fields', 'ids');
        $q->set('show_past_lottery', FALSE);
      }
    }