如何填充 Woocommerce 手动订单的元字段

How can I populate meta fields of a Woocommerce manual order

我为我的 Woocommerce 订单定义了两个自定义字段。我使用 WooCommerce Admin Custom Order Fields extension 创建了这两个字段。

当我手动创建订单时(/wp-admin/post-new.php?post_type=shop_order),我可以看到那些字段,我可以成功添加数据并保存命令。

但是,我希望在代码中自动填充其中一个字段。我正在尝试使用以下代码找出该自定义字段的元键,以便我可以使用 update_post_meta() 来填充它,但是当我 运行 它时,这并没有给我任何东西:

add_action('woocommerce_process_shop_order_meta', 'process_offline_order', 10, 2);
function process_offline_order ($post_id, $post) {
    echo '<pre>';
    print_r(get_post_meta($post_id));
    die();
}

该扩展的文档告诉我,我可以使用 get_post_meta($post_id, '_wc_acof_2') 之类的东西,其中 2 是该自定义字段的 ID,我也尝试过但没有成功。它没有返回任何东西。

下面是我的配置屏幕截图:

知道如何 access/populate 这些字段吗?如果我使用的字段不正确,应该使用什么挂钩?

您应该尝试以这种方式使用 "save_post" 动作挂钩:

// Saving (Updating) or doing an action when submitting
add_action( 'save_post', 'update_order_custom_field_value' );
function update_order_custom_field_value( $post_id ){

    // Only for shop order
    if ( 'shop_order' != $_POST[ 'post_type' ] )
        return $post_id;

    // Checking that is not an autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
    if ( ! current_user_can( 'edit_shop_order', $post_id ) && ! current_user_can( 'edit_shop_orders', $post_id ) )
        return $post_id;

    // Updating custom field data
    if( isset( $_POST['wc-admin-custom-order-fields'][2] ) ) {
        // The new value
        $value = 'Green';

        // OR Get an Order meta data value ( HERE REPLACE "meta_key" by the correct metakey slug)
        // $value = get_post_meta( $post_id, 'meta_key', true ); // (use "true" for a string or "false" for an array)

        // Replacing and updating the value
        update_post_meta( $post_id, '_wc_acof_2', $value );
    }
}


// Testing output in order edit pages (below billing address):
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_order_custom_field_value' );
function display_order_custom_field_value( $order ){
    foreach( get_option( 'wc_admin_custom_order_fields' ) as $id => $field ){
        $value = get_post_meta( $order->get_id(), '_wc_acof_'.$id, true );
        // Define Below the custom field ID to be displayed
        if( $id == 2 && ! empty( $value ) ){
            echo '<p><strong>' . $field['label'] . ':</strong> ' . $value . '</p>';
        }
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。