自定义 WooCommerce 产品查询不起作用

Custom WooCommerce Product Query is not working

我正在尝试创建此自定义产品查询,以仅在具有以下 tax_query/shop 页面上显示产品。但是没用。

我也试过 woocommerce_product_query 钩子。

感谢任何建议!

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')),    
);   

因此,为了有条件地检查您是否在 shop page 上,您可以使用以下 woocommerce 函数:

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

另外,为了编写 tax_query,您可以将所有 arrays/filters 分配给一个变量,如下所示:

$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...
  // )
);

所以最终的代码应该是这样的:

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);
  }
}