【问题标题】:Custom WooCommerce Product Query is not working自定义 WooCommerce 产品查询不起作用
【发布时间】:2021-10-24 18:53:39
【问题描述】:

我正在尝试创建此自定义产品查询,以便仅在 /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')),    
);   

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce woocommerce-theming


    【解决方案1】:

    因此,为了有条件地检查您是否在 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);
      }
    }
    

    【讨论】:

    • 谢谢,我更新了我的问题,提供了有关查询来源的更多详细信息。
    • 刚刚更新了我的答案。让我知道你是否能够让它工作。
    猜你喜欢
    • 1970-01-01
    • 2019-07-02
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多