【问题标题】:How do I show sold/out of stock items in a certain Woocommerce category archive page, but not display them in others?如何在某个 Woocommerce 类别存档页面中显示已售出/缺货的商品,但不显示在其他商品中?
【发布时间】:2020-04-27 03:54:27
【问题描述】:

我想在一个类别存档页面上显示“缺货”商品:“已售商品”。

所有其他类别都需要隐藏其缺货商品。

“从目录中隐藏缺货商品”,在 WC 设置中未勾选。

我有以下代码,它成功隐藏了缺货商品,但我无法让 has_term() 函数正常工作并过滤掉“已售商品”页面。

我相信这可能是因为我正在使用“pre_get_posts”,并且可能在添加“Sold Items”术语之前触发。

最适合参与的行动是什么?还是我需要把它分成两个钩子?

add_action( 'pre_get_posts', 'VG_hide_out_of_stock_products' ); 
function VG_hide_out_of_stock_products( $q ) {

    if ( ! $q->is_main_query() || is_admin() ) {
         return;
    }

    global $post;
    if ( !has_term( 'Sold Items', 'product_cat', $post->ID ) ) {
        if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) {
            $tax_query = (array) $q->get('tax_query');
            $tax_query[] = array(
                'taxonomy' => 'product_visibility',
                'field' => 'term_taxonomy_id',
                'terms' => array( $outofstock_term->term_taxonomy_id ),
                'operator' => 'NOT IN'
            );
            $q->set( 'tax_query', $tax_query );
        }
    } 
}

【问题讨论】:

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


    【解决方案1】:

    最好使用高级 WooCommerce 特定的过滤器钩子,而不是可能导致头痛和麻烦的低级 WordPress 钩子。 (例如pre_get_posts) 对于您的情况,我建议woocommerce_product_query_tax_query 过滤器挂钩。 假设您有一个包含所有缺货产品的类别,带有 slug sold-items,最终代码可能是这样的:

    add_filter( 'woocommerce_product_query_tax_query', 'vg_hide_out_of_stock_products' );
    
    function vg_hide_out_of_stock_products( $tax_query ) {
    
        if( !is_shop() && !is_product_category() && !is_product_tag() ) {
            return $tax_query;
        }
        if( is_product_category('sold-items') ) {
            $tax_query[] = array(
                'taxonomy' => 'product_visibility',
                'field'    => 'slug',
                'terms'    => ['outofstock'],
                'operator' => 'IN',
            );
        } else {
            $tax_query[] = array(
                'taxonomy' => 'product_visibility',
                'field'    => 'slug',
                'terms'    => ['outofstock'],
                'operator' => 'NOT IN',
            );
        }
        return $tax_query;
    }
    

    P.S: PHP 中的函数名不区分大小写:)

    【讨论】:

    • 你是我的英雄!我今天才重新开始玩这个。感谢您帮助解决一个问题,即使它已经一个月大了,你让我很开心:)
    • @daveidivide 很高兴能帮到你:)
    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2023-03-16
    • 2020-11-03
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    相关资源
    最近更新 更多