在Woocommerce管理订单页面中保存订单商品自定义字段

问题描述 投票:1回答:1

我在每个行产品的后台订单中添加了自定义字段:

我的问题是我不知道如何保存这些字段。

你能帮我么?

function cfwc_create_custom_field() {
 $args = array(
'id' => 'custom_text_field_title',
'label' => __( 'Custom Text Field Title', 'cfwc' ),
'class' => 'cfwc-custom-field',
'desc_tip' => true,
'description' => __( 'Enter the title of your custom text field.', 'ctwc' 
 ),
 );
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_before_order_itemmeta', 'cfwc_create_custom_field' );
php wordpress woocommerce custom-fields orders
1个回答
0
投票

要添加和保存自定义字段以在管理订单编辑页面中订购“订单项”,您将使用以下内容:

// Add a custom field
add_action( 'woocommerce_before_order_itemmeta', 'add_order_item_custom_field', 10, 2 );
function add_order_item_custom_field( $item_id, $item ) {
    // Targeting line items type only
    if( $item->get_type() !== 'line_item' ) return;

    woocommerce_wp_text_input( array(
        'id'            => 'cfield_oitem_'.$item_id,
        'label'         => __( 'Custom Text Field Title', 'cfwc' ),
        'description'   => __( 'Enter the title of your custom text field.', 'ctwc' ),
        'desc_tip'      => true,
        'class'         => 'woocommerce',
        'value'         => wc_get_order_item_meta( $item_id, '_custom_field' ),
    ) );
}

// Save the custom field value
add_action('save_post_shop_order', 'save_order_item_custom_field_value');
function save_order_item_custom_field_value( $post_id ){
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
        return $post_id;

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    if ( ! current_user_can( 'edit_shop_order', $post_id ) )
        return $post_id;

    $order = wc_get_order( $post_id );

    // Loop through order items
    foreach ( $order->get_items() as $item_id => $item ) {
        if( isset( $_POST['cfield_oitem_'.$item_id] ) ) {
            wc_update_order_item_meta( $item_id, '_custom_field', sanitize_text_field( $_POST['cfield_oitem_'.$item_id] ) );
        }
    }
}

// Optionally Keep the new meta key/value as hidden in backend
add_filter( 'woocommerce_hidden_order_itemmeta', 'additional_hidden_order_itemmeta', 10, 1 );
function additional_hidden_order_itemmeta( $args ) {
    $args[] = '_custom_field';
    return $args;
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。

© www.soinside.com 2019 - 2024. All rights reserved.