Skip to content
Advertisement

Display orders items names excluding a product category in WooCommerce

With WooCommerce, I have faced a problem on my code below: I have tried skip specific category from my loop. Product has been skipped but some remaining products are showing multiple times:

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>';
        }
    }
}

How can I avoid this item name repetition on this loop?

Advertisement

Answer

The variable $product_cat_id is not defined in your code, so your if statement is always true.

To check for a product category in order items, use instead the conditional function has_term(). It will avoid getting product name displayed multiple times and items that belong to 38355 category ID will be excluded.

Here is your revisited simplified code version:

$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 );

Now it should work as expected

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement