使用 WooCommerce,我在下面的代码中遇到了一个问题:我尝试从循环中跳过特定类别。产品已被跳过,但一些剩余产品显示多次:
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$terms = get_the_terms( $product_id, 'product_cat' );
foreach ($terms as $term) {
if ($product_cat_id != 38355) { //category id
echo $name = $item->get_name().'<br>';
}
}
}
如何避免此循环中的此项目名称重复?
该变量$product_cat_id
未在您的代码中定义,因此您的 if 语句始终为真。
要检查订单商品中的产品类别,请改用条件函数has_term()
。这将避免多次显示产品名称,并且38355
将排除属于类别 ID 的项目。
这是您重新访问的简化代码版本:
$item_names = array(); // Initializing
foreach ( $order->get_items() as $item ) {
// Excluding items from a product category term ID
if ( ! has_term( 38355, 'product_cat', $item->get_product_id() ) ) {
$item_names[] = $item->get_name();
}
}
// Output
echo implode( '<br>', $item_names );
现在它应该按预期工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句