【问题标题】:How to update Order meta data, from a WooCommerce Action如何从 WooCommerce 操作更新订单元数据
【发布时间】:2021-03-04 11:41:04
【问题描述】:

我正在尝试通过运行Order action 将一些自定义元数据添加到 WooCommerce 订单。

这是我的代码:

function custom_add_order_actions( $actions ){
    global $theorder;
    $actions['my_custom_action'] = 'My custom action';
    return $actions;
}
add_action( 'woocommerce_order_actions', 'custom_add_order_actions' );



function custom_add_single_action( $order ){

    // Non of these change anything on the order
    $order->set_billing_first_name( 'A new test name' );
    $order->update_post_meta( 'a_test_field', 'Test field value' );
    update_post_meta( $order->get_id(), 'a_test_field', 'Some other value' );

    // $order->save(); // I even tried adding this as well, but it doesn't change anything.
}
add_action( 'woocommerce_order_action_my_custom_action', 'custom_add_single_action' );

如何从操作中更改订单(或具体来说,订单的 post_meta 字段)?


一个例子

假设我添加了一个 post_meta 字段,其字段名称(键):a_test_field。 它目前是一个 ACF 字段,但对于常规的 WordPress 自定义字段来说是一样的。

如果我更改字段的值并按“更新”,则值会更改:

到目前为止一切顺利。现在该字段的值为 'Foobar'。

奇怪的是,即使我这样做:

add_action( 'woocommerce_order_action_my_custom_action', 'custom_add_single_action' );
function custom_add_single_action( $order ){
    update_post_meta( $order->get_id(), 'a_test_field', 'A new value' );
    die(); // This die is vital, to make the change in the database.
}

然后我可以看到数据库中的值更改为“新值”。

但如果我这样做:

add_action( 'woocommerce_order_action_my_custom_action', 'custom_add_single_action' );
function custom_add_single_action( $order ){
    $order->update_post_meta( 'a_test_field', 'A new value' );
    // No die(); here... 
}

那么数据库中的值仍然是“Foobar”。

【问题讨论】:

    标签: woocommerce


    【解决方案1】:

    很抱歉,以下稍微重新审视的代码可以工作(选择操作并单击按钮箭头)

    add_action( 'woocommerce_order_actions', 'add_custom_order_action' );
    function add_custom_order_action( $actions ){
        $actions['my_custom_action'] = __('My custom action', 'WooCommerce');
    
        return $actions;
    }
    
    add_action( 'woocommerce_order_action_my_custom_action', 'triggered_custom_order_action' );
    function triggered_custom_order_action( $order ){
        $order->update_meta_data( '_test_1_custom_field', 'AAFFBB9977' );
        $order->save();
    
        update_post_meta( $order->get_id(), '_test_2_custom_field', 'Some other value' );
    }
    

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

    注意:订单操作主要用于您想做的事情之外的其他事情。


    现在,当使用元框输入字段 (如您所展示的那样),在提交时,您应该保存该字段值使用动作钩子save_post_shop_order 就像在那些相关线程中一样:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 2019-06-14
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多