在 WooCommerce 中显示不包括产品类别的订单项目名称

问题描述

使用 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 语句始终为真。

要检查订单商品中的产品类别,请改用 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 );

现在它应该按预期工作