1

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

我正在使用WooCommerce MultiStep Checkout Wizard高级插件和一个特定的钩子

add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep');

我有点迷茫,找不到太多我需要用来获取它 的文档。

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

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

1 回答 1

4

您可以先尝试使用您的方法" 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 是在客户提交订单时生成的,而不是在结帐页面之前生成的。
所以在这种情况下,得到一个空数组是很正常的。

于 2016-06-10T15:07:55.493 回答