Tristan .L
Tristan .L

Reputation: 849

Get category id by product in WooCommerce

What I want to do is make a foreach loop to get all products and from those products I want to get their category id. This so I can later check for certain categories.

$order = new WC_Order( $order_id );
$items = $order->get_items();

foreach ( $items as $item ) {
    $product_catagory_id .= $item['catagory_id']; //in between these brackets I need a value that gives me the catagory id.
}

//Some validation here if one of the catagorie_id's was found.
//I can build this. It's not part of the question

After some comments, this is where I'm stranded:

$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
    $product_id = $item['product_id'];
    var_dump($product_id);
    $terms = get_the_term_list( $product_id, 'term_id' );
    var_dump($terms);
}

This results in the following:

string(2) "79"
object(WP_Error)#9148 (2) {
    ["errors"]=>
        array(1) {
        ["invalid_taxonomy"]=>
            array(1) {
                [0]=>
                string(19) "Ongeldige taxonomie" //invalid taxonomy
            }
        }
    ["error_data"]=>
    array(0) {
    }
}

So the product ID is read perfectly, I can work with that but the category isn't returned properly.

Upvotes: 4

Views: 45876

Answers (2)

mohamad abasi
mohamad abasi

Reputation: 1

$terms = get_the_terms ( $product_id, 'product_cat' );
foreach ( $terms as $term ) {
 $cat_id = $term->term_id;
    
}
     

Upvotes: -1

zipkundan
zipkundan

Reputation: 1774

Try

$terms = get_the_terms ( $product_id, 'product_cat' );
foreach ( $terms as $term ) {
     $cat_id = $term->id;
}

Try var_dump($terms); to rightly analyse how to get category id.

Hope this helps.

Upvotes: 14

Related Questions