Save Order item custom field in Woocommerce Admin order pages

送分小仙女□ 提交于 2021-01-19 08:00:10

问题


I have add custom fields in back office order for each line products :
(source: com-pac.ovh)

My problem is that I don't know how to save this fields.

Can you please help me?

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' );

回答1:


To add and save a custom field to order "line items" in admin order edit pages you will use something like:

// 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;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.



来源:https://stackoverflow.com/questions/54402176/save-order-item-custom-field-in-woocommerce-admin-order-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!