在WooCommerce中按产品获取类别ID

时间:2016-04-15 08:11:41

标签: php foreach woocommerce

我想做的是制作一个foreach循环来获取所有产品,并从那些我希望获得类别ID的产品中获取。这样我以后可以检查某些类别。

$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

经过一番评论后,这就是我陷入困境的地方:

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

这导致以下结果:

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) {
    }
}

因此,产品ID读取完美,我可以使用,但类别未正确返回。

1 个答案:

答案 0 :(得分:5)

尝试

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

尝试var_dump($terms);正确分析如何获取类别ID。

希望这有帮助。