在 Woocommerce 中排除相关产品 ID

时间:2023-01-16
本文介绍了在 Woocommerce 中排除相关产品 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

function woocommerce_output_related_products() {

    $args = array(
        'posts_per_page' => 4,
        'columns'        => 4,
        'orderby'        => 'rand', // @codingStandardsIgnoreLine.
        'post__not_in' => array(502,281)
    );

    woocommerce_related_products( apply_filters( 'woocommerce_output_related_products_args', $args ) );
}

我将此函数从 includes/wc-template-functions.php 复制到我的主题的functions.php

I copied this function from includes/wc-template-functions.phpinto my theme's functions.php

为了验证我的更改是否有效,我将 posts_per_page 更改为 3,它只查询 3 而不是 4.

To verify that my changes would work I changed the posts_per_page to 3 and it queried only 3 instead of 4.

我需要排除一些产品,但 post__not_in 不起作用.

I need to exclude a few products, but post__not_in is not working.

我做错了吗?我还能如何排除使用此功能的产品?

Am I doing something wrong? How else can I exclude products using this function?

我用这个函数输出产品:woocommerce_output_related_products();

I'm outputting the products with this function: woocommerce_output_related_products();

好讨厌的问题.我根本无法从这里排除产品.有人可以帮忙吗?

such an obnoxious problem. I simply cannot exclude products from here. can anyone help?

我也试过这个:

add_filter( 'woocommerce_output_related_products_args', function( $args ) { 
    $args = wp_parse_args( array(  "post__not_in" => array('502','281') ), $args );
    return $args;
});

我做了 print_r($args) 并且它显示我的post__not_in"被添加了,但产品仍然存在.我有正确的身份证.

i did print_r($args) and it showed that my "post__not_in" was being added, but the products are still there. I have the right ID.

推荐答案

改用 woocommerce_related_products 过滤器钩子,这样:

Use the woocommerce_related_products filter hook instead, this way:

add_filter( 'woocommerce_related_products', 'exclude_related_products', 10, 3 );
function exclude_related_products( $related_posts, $product_id, $args ){
    // HERE set your product IDs to exclude
    $exclude_ids = array('502','281');

    return array_diff( $related_posts, $exclude_ids );
}

代码位于活动子主题(或活动主题)的 function.php 文件中.经测试有效.

这篇关于在 Woocommerce 中排除相关产品 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:添加自定义“预订"按钮到 WooCommerce 产品单页 下一篇:基于购物车的 WooCommerce 登录重定向

相关文章

最新文章