【问题标题】:How to hide products from the products shortcode 'woocommerce_shortcode_products_query' using product ids如何使用产品 ID 从产品简码“woocommerce_shortcode_products_query”中隐藏产品
【发布时间】:2022-02-06 05:07:43
【问题描述】:

我正在使用 woocommerce 产品简码在产品页面上显示一些相关产品。

产品简码如下:

do_shortcode('[products limit="6" columns="6"]');

我正在使用woocommerce_shortcode_products_query 过滤器修改简码,如下所示:

add_filter( 'woocommerce_shortcode_products_query', function( $query_args, $atts, $loop ){

    $product_id = 12345;

    // Remove out of stock results
    $query_args['meta_query'] = array( array(
        'key'     => '_stock_status',
        'value'   => 'outofstock',
        'compare' => 'NOT LIKE',
    ) );

    // Remove the current product by id
    $query_args['tax_query'] = array( array(
        'taxonomy' => 'product', 
        'field' => 'id', 
        'terms' => array($product_id), // Remove this product from the shortcode results
        'operator' => 'NOT IN',
    ) );


    
    return $query_args;

}, 10, 3);

第一部分通过删除缺货结果来工作。

第二部分不起作用,我无法弄清楚如何从查询中排除特定产品。

谷歌搜索问题时的所有结果都在谈论 product_cat 分类,但是我不想删除某个类别中的产品,我想删除当前产品by id,以便仅在短代码中显示其他相关产品。

所以我的问题是:如何使用“woocommerce_shortcode_products_query”从产品简码中隐藏当前产品

【问题讨论】:

    标签: wordpress woocommerce wordpress-theming wordpress-shortcode woocommerce-theming


    【解决方案1】:

    您需要使用WP_Query'post__not_in' 参数。

    所以你的代码应该是这样的:

    add_filter('woocommerce_shortcode_products_query', function ($query_args, $atts, $loop) {
    
        $product_ids = array(1, 2, 3);
    
        $query_args['meta_query'] = array(array(
            'key'     => '_stock_status',
            'value'   => 'outofstock',
            'compare' => 'NOT LIKE',
        ));
    
        $query_args['post__not_in'] = $product_ids;
    
    
        return $query_args;
    }, 10, 3);
    

    这将排除 ID 为 123 的产品。您可以将不同的产品 ID 传递给 $product_ids 变量。

    您也可以只排除一种产品,只需将一个 id 传递给 $product_ids 变量! (例如$product_ids = array(37)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      相关资源
      最近更新 更多