【问题标题】:Automatically add custom order shipping item meta data in WooCommerce在 WooCommerce 中自动添加自定义订单运输项目元数据
【发布时间】:2021-07-13 13:36:52
【问题描述】:

我知道如何在订单发货方式上添加元数据:

$shippingMethodItem->update_meta_data('num_packages', 0);

但我想在下订单或有人手动添加/编辑订单商品时自动添加/更新此元数据。

我已经试过了,没有结果:

add_action( 'woocommerce_checkout_create_order_shipping_item', [$this, 'actionCheckoutCreateOrderShippingItem'] );

...

public function actionCheckoutCreateOrderShippingItem ($shippingMethodItem, $package_key, $package, $order)
{
    $shippingMethodItem->update_meta_data( 'num_packages', 0);
    $shippingMethodItem->save();
}

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce orders


    【解决方案1】:

    以下内容也将通过结帐和/或手动管理订单在订单上添加自定义特定订单“运输”项目元数据:

    // For new orders via checkout
    add_action( 'woocommerce_checkout_create_order_shipping_item', 'action_checkout_create_order_shipping_item', 10, 4 );
    function action_checkout_create_order_shipping_item ( $item, $package_key, $package, $order ){
        $item->update_meta_data( 'num_packages', 0 );
    }
    
    // For manual admin orders
    add_action( 'woocommerce_saved_order_items', 'action_saved_order_items_callback', 10, 2 );
    function action_saved_order_items_callback( $order_id, $items ) {
        if ( isset( $items['shipping_method_id'] ) ) {
            foreach( $items['shipping_method_id'] as $item_id ) {
                $num_packages = wc_get_order_item_meta($item_id, 'num_packages');
    
                if ( empty($num_packages) || $num_packages != 0 ) {
                    wc_update_order_item_meta( $item_id, 'num_packages', 0 );
                }
            }
        }
    }
    

    代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。


    要在带有类 (OOP) 的插件中使用此代码,请在构造函数中添加以下内容:

    // For checkout order
    add_action( 'woocommerce_checkout_create_order_shipping_item', [$this, 'action_checkout_create_order_shipping_item'], 10, 4 );
    // For checkout order
    add_action( 'woocommerce_saved_order_items', [$this, 'action_saved_order_items_callback'], 10, 2 );
    

    以及构造函数之外的以下内容:

    public function action_checkout_create_order_shipping_item ( $item, $package_key, $package, $order ){
        $item->update_meta_data( 'num_packages', 0 );
    }
    
    public function action_saved_order_items_callback( $order_id, $items ) {
        if ( isset( $items['shipping_method_id'] ) ) {
            foreach( $items['shipping_method_id'] as $item_id ) {
                $num_packages = wc_get_order_item_meta($item_id, 'num_packages');
    
                if ( empty($num_packages) || $num_packages != 0 ) {
                    wc_update_order_item_meta( $item_id, 'num_packages', 0 );
                }
            }
        }
    }
    

    【讨论】:

    • 非常感谢 :)
    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多