首页 > 解决方案 > 自定义 WooCommerce 产品查询不起作用

问题描述

我正在尝试创建此自定义产品查询,以仅在/shop页面上显示具有以下内容的产品tax_query。但它不起作用。

我也试过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')),    
);   

标签: phpwordpresswoocommercehook-woocommercewoocommerce-theming

解决方案


因此,对于您的条件检查,您是否shop page可以使用以下 woocommerce 功能:

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

此外,为了编写您的tax_query内容,您可以将所有数组/过滤器分配给一个变量,如下所示:

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

推荐阅读