繁体   English   中英

Woocommerce 从商店页面中排除某些类别

[英]Woocommerce Excluding Certain Category from Shop Page

试图从我的 WooCommerce 商店页面中排除一个类别

我正在使用此代码,但它会破坏我网站的属性过滤器链接:

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;

    if ( ! is_admin() && is_shop() ) {

        $q->set( 'tax_query', array(array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'samples' ), 
           'operator' => 'NOT IN'
        )));

     }

     remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

此解决方案从商店页面中排除了类别。 但问题是,排除类别的类别存档页面显示没有可用的产品。

我有不想在商店页面上登记的电子书类别。 我为电子书创建了一个单独的菜单项,我想在这里列出电子书类别中的所有书籍。

如何实现这一目标?

更新

我添加了if (!$q->is_main_query() || !is_shop()) return; 到动作钩子,它解决了我上面提到的问题。 此行仅从商店页面排除类别,但是当从菜单(类别页面)直接访问排除的类别时,所有产品都列出良好。

function custom_pre_get_posts_query( $q ) {

if (!$q->is_main_query() || !is_shop()) return;

$tax_query = (array) $q->get( 'tax_query' );

$tax_query[] = array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'ebooks' ),
       'operator' => 'NOT IN'
);


$q->set( 'tax_query', $tax_query );

}

add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

您可以使用woocommerce_product_query钩子,它与pre_get_posts非常相似,只是它已经具有适当的条件逻辑。 还有一个woocommerce_product_query_tax_query过滤器,但我不确定 WooCommerce 2.6 中是否存在它,或者它是否是 2.7 beta 中的新功能。

add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    $q->set( 'tax_query', array(array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'samples' ), 
       'operator' => 'NOT IN'
    )));

}

编辑过滤是通过分类查询完成的,在上面的例子中,我们完全覆盖了税务查询。 我现在无法测试这是否有效(并且数组数组很棘手,所以我可能搞砸了),但理论上我们需要将新约束与 WooCommerce 生成的现有分类查询合并。

add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    $tax_query = (array) $q->get( 'tax_query' );

    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'samples' ), 
           'operator' => 'NOT IN'
    );


    $q->set( 'tax_query', $tax_query );

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM