【问题标题】:Hide products having a specific product category in Woocommerce在 Woocommerce 中隐藏具有特定产品类别的产品
【发布时间】:2018-03-13 09:00:48
【问题描述】:

我们使用以下代码隐藏具有“未分类”类别的产品:

add_action('pre_get_posts', 'custom_pre_get_posts_query');
function custom_pre_get_posts_query( $q ) {
    if (!$q->is_main_query()) return;
    if (!$q->is_post_type_archive()) return;
  $q->set('tax_query', array(
    array(
      'taxonomy' => 'product_cat',
      'field'    => 'slug',
      'terms'    => 'ukategorisert',
      'operator' => 'NOT IN',
    )
  ));
    remove_action('pre_get_posts', 'custom_pre_get_posts_query');
}

但由于某种原因,存档最终会在每个页面上显示不同数量的产品。好像产品被隐藏了,但在分页中仍然算作产品?

我们找不到此问题的原因或解决方案。请帮忙。

【问题讨论】:

    标签: php wordpress woocommerce product custom-taxonomy


    【解决方案1】:

    您应该使用相关的专用 Woocommerce 操作和过滤器挂钩之一,而不是使用 pre_get_posts 挂钩函数。

    试试这个:

    add_filter('woocommerce_product_query_tax_query', 'custom_product_query_tax_query', 10, 2 );
    function custom_product_query_tax_query( $tax_query, $query ) {
        if( is_admin() ) return $tax_query;
    
        // HERE Define your product category SLUGs to be excluded
        $terms = array( 'ukategorisert' ); // SLUGs only
    
        // The taxonomy for Product Categories
        $taxonomy = 'product_cat';
    
        $tax_query[] = array(
            'taxonomy' => $taxonomy,
            'field'    => 'slug', // Or 'name' or 'term_id'
            'terms'    => $terms,
            'operator' => 'NOT IN', // Excluded
        );
    
        return $tax_query;
    }
    

    此代码位于您的活动子主题(或主题)的 function.php 文件中。它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      相关资源
      最近更新 更多