How to save and display user meta from Woocommerce order admin

后端 未结 1 1252
旧时难觅i
旧时难觅i 2021-01-25 01:21

Customers have an extra field called billing_ean as part of their billing address.

I\'m using the following code to load, edit, and save their EAN number fr

相关标签:
1条回答
  • 2021-01-25 02:15

    Try the following instead, where the field displayed in order edit pages and the value is saved to order meta data and user meta data…

    Your revisited code:

    add_action( 'woocommerce_admin_order_data_after_billing_address', 'customer_ean_edit' );
    function customer_ean_edit( $order ){
        $value = get_user_meta( $order->get_customer_id(), 'billing_eannr', true );
        ?>
        <div class="edit-address"><?php
            woocommerce_wp_text_input( array(
                'id' => 'billing_eannr',
                'label' => __('EAN nr.:', 'woocommerce'),
                'placeholder' => '',
                'value' => $value,
                'wrapper_class' => 'form-field-wide'
            ) );
        ?></div><?php
    }
    
    
    add_action('save_post_shop_order', 'customer_ean_save', 50, 3 );
    function customer_ean_save( $post_id, $post, $update ) {
    
        // 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 ) )
            return $post_id;
    
        if( isset($_POST['billing_eannr']) ) {
            $order = wc_get_order( $post_id );
            // Update order post meta data
            update_post_meta( $post_id, 'billing_eannr', sanitize_text_field( $_POST['billing_eannr'] ) );
            // Update user meta data
            update_user_meta( $order->get_customer_id(), 'billing_eannr', sanitize_text_field( $_POST['billing_eannr'] ) );
        }
    }
    

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

    0 讨论(0)
提交回复
热议问题