gpt4 book ai didi

php - 在我的 WooCommerce 相关产品小部件中排除特定类别

转载 作者:行者123 更新时间:2023-12-04 10:46:42 27 4
gpt4 key购买 nike

我所有的 WooCommerce 产品都分配了两个类别。第一个类别称为“所有产品”,所有产品都被分配。第二类取决于产品,可能是电影、书籍、工具等。

由于每个产品都被分配到“所有产品”类别,因此在产品页面上的相关产品小部件中,您会看到每个产品,而不仅仅是第二个(更具体的)产品类别。

我正在尝试在 functions.php 中添加一些代码,这些代码将忽略“所有产品”作为相关产品小部件的类别,但仍会显示已分配产品的第二个类别的相关产品。

到目前为止,我有这段代码,它将相关产品小部件全部隐藏在一起。我认为这是因为每个产品都被分配了 slug“all-products”,所以它删除了小部件而不是计算产品分配的第二个类别。

add_filter( 'woocommerce_related_products', 'exclude_product_category_from_related_products', 10, 3 );
function exclude_product_category_from_related_products( $related_posts, $product_id, $args ){
// HERE define your product category slug
$term_slug = 'all-products';

// Get the product Ids in the defined product category
$exclude_ids = wc_get_products( array(
'status' => 'publish',
'limit' => -1,
'category' => array($term_slug),
'return' => 'ids',
) );

return array_diff( $related_posts, $exclude_ids );
}

如何编辑此代码,使其隐藏“所有产品”类别,使其不在相关产品中显示,但仍显示其他指定类别的相关产品?

最佳答案

您最好使用 woocommerce_get_related_product_cat_terms。您可以使用它来删除用于获取产品的类别数组中的 'all-products'

add_filter( 'woocommerce_get_related_product_cat_terms', 'exclude_product_category_from_related_products' );
function exclude_product_category_from_related_products( $cats_array ) {

$term = get_term_by('slug', 'all-products', 'product_cat');

if ( $term && ($key = array_search($term->term_id, $cats_array)) !== false) {
unset($cats_array[$key]);
}

return $cats_array;
}

关于php - 在我的 WooCommerce 相关产品小部件中排除特定类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59674533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com