仅计算顶级WooCommerce产品类别以进行自定义运输计算 [英] Count only top level WooCommerce product categories form custom shipping calculations
问题描述
我正在使用 增加我在上一个问题中在WooCommerce购物车中找到的每个类别的运输成本计数 。
I am using Increase Shipping cost per categories count found in WooCommerce cart answer code from my previous question.
如何从产品类别ID的数组中排除子类别,以仅保留顶部类别?
How to exclude subcategories from the array of product categories Ids, to keep only top categories?
根据此自定义计算的解决方案,还包括子类别来计算运输成本。
我需要将它们排除在外,因为它们仅用于对项目进行排序。
According to the solution for this custom calculation, Sub-categories are also included for calculating shipping costs. I would need them to be excluded since they are used only for sorting items.
我尝试在数组中添加过滤器,但制动了站点。
I tried with adding a filter to the array but brakes the site.
推荐答案
仅计算顶级产品类别(不包括子类别),您将替换为 增加在WooCommerce购物车中找到的每个类别的运输费用 答案代码,以下代码块:
To only count top level product categories (not subcategories), you will replace in Increase Shipping cost per categories count found in WooCommerce cart answer code, the following code block:
// Loop through cart items for the current shipping package
foreach( $package['contents'] as $cart_item ){
$term_ids = array_merge(
$term_ids,
(array) $cart_item['data']->get_category_ids()
);
}
与此一起:
// Loop through cart items for the current shipping package
foreach( $package['contents'] as $cart_item ){
$terms = wp_get_post_terms( $cart_item['product_id'], 'product_cat' );
// Loop through product categories terms for current cart item
foreach ($terms as $term ) {
// Only top level product category terms
if ( $term->parent == 0 ) {
// Set the term id in the array
$term_ids[] = $term->term_id;
}
}
}
经测试可正常工作。
这篇关于仅计算顶级WooCommerce产品类别以进行自定义运输计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!