【问题标题】:How to get categories from an order at checkout in WooCommerce?如何在 WooCommerce 结账时从订单中获取类别?
【发布时间】:2016-10-10 23:29:57
【问题描述】:

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

我正在使用WooCommerce MultiStep Checkout Wizard 高级插件和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);

【问题讨论】:

    标签: php wordpress woocommerce checkout hook-woocommerce


    【解决方案1】:

    你可以先试试你的方法"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');
    

    更新 - 经过一番思考:

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

    【讨论】:

    • 您好,很抱歉回复晚了,两者都不适合我。我只在开始时使用代码的第一位并尝试获取 var 转储。两个 var 转储都是空数组。有什么建议吗?如果我们能搞定的话,我会给你买点龙舌兰酒:)
    • 是的,我也试过了。只是没有循环的第一部分。只是一个空数组。
    • 刚刚对帮助表示赞同这是我在其他地方读到的内容,它不仅对我有用。
    • 不,两者都只给出空数组。
    猜你喜欢
    • 2020-12-09
    • 2020-05-08
    • 2014-03-05
    • 2021-07-14
    • 2019-01-26
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2021-04-02
    相关资源
    最近更新 更多