使用 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>';
}
}
}
如何避免此循环中的此项目名称重复?
最佳答案
您的代码中 undefined variable $product_cat_id
,因此您的 if 语句始终为 true。
要检查订单商品中的产品类别,请使用 conditional function 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 );
现在它应该按预期工作
关于php - 在 WooCommerce 中显示不包括产品类别的订单项目名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66560049/