在 WooCommerce 中按产品获取类别 ID

问题描述 投票:0回答:2

我想做的是创建一个 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 已完美读取,我可以使用它,但类别未正确返回。

php foreach woocommerce
2个回答
14
投票

尝试

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

尝试

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

希望这有帮助。


0
投票
$terms = get_the_terms ( $product_id, 'product_cat' );
foreach ( $terms as $term ) {
 $cat_id = $term->term_id;
    
}
     
© www.soinside.com 2019 - 2024. All rights reserved.