首页 文章

如何在结账时从WooCommerce获取订单中的类别?

提问于
浏览
1

我想在WooCommerce结账时获取购物车中商品的类别 . 我想提取它然后将它放在我的自定义结帐中的字段中 .

我正在使用WooCommerce MultiStep Checkout Wizard premium插件和specific hook

add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep');

我找到了很多documentation,因为我需要用它来获得它 .

我试图让项目出现,但我只是得到一个空数组 .

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

1 回答

  • 3

    您可以先尝试使用您的方法 "new WC_Order( $order_id );" ,这样:

    function destinationStep( $order_id )
    
        global $woocommerce; 
    
        $order = new WC_Order( $order_id );
        $items = $order->get_items(); 
        // echo var_dump($items);
    
        //----
        foreach ($items as $key => $item) {
            $product_name = $item['name'];
            $product_id = $item['product_id'];
            $terms = get_the_terms( $product_id, 'product_cat' );
            // echo var_dump($terms);
    
            foreach ( $terms as $term ) {
                // Categories by slug
                $product_cat_slug= $term->slug;
            }
        }
    
    add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep', 10, 1);
    

    如果仍然无效,请尝试使用 "new WC_Order($post->ID)" 方法:

    function destinationStep()
    
        global $woocommerce, $post; 
    
        $order = new WC_Order($post->ID);
        $items = $order->get_items(); 
        // echo var_dump($items);
    
        //----
        foreach ($items as $key => $item) {
            $product_name = $item['name'];
            $product_id = $item['product_id'];
            $terms = get_the_terms( $product_id, 'product_cat' );
            // echo var_dump($terms);
    
            foreach ( $terms as $term ) {
                // Categories by slug
                $product_cat_slug= $term->slug;
            }
        }
    
    add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep');
    

    Update - 经过一番思考:

    您无法获得''post_type'=>'shop_order'的订单ID,因为它尚不存在 . 此订单ID是在客户提交订单时生成的,而不是在结帐页面之前生成的 . 所以在这种情况下,获得一个空数组是正常的 .

相关问题