首页 > 解决方案 > 为已通过 WooCommerce 管理员订单页面添加的元数据添加自定义配置文件字段

问题描述

我使用来自 Woocommerce 订单管理的 How to save and display user meta 中的解决方案来添加和创建可以保存到客户资料中的订单元数据。

现在我想将此字段显示为“客户资料”页面中的可编辑字段。

这是我所管理的,它似乎工作得很好。只是检查我是否做得正确。

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("Visma Customer Information", "blank"); ?></h3>

    <table class="form-table">
    <tr>
        <th><label for="billing_visma"><?php _e("Customer Number"); ?></label></th>
        <td>
            <input type="number" min="1" name="billing_visma" id="billing_visma" value="<?php echo esc_attr( get_the_author_meta( 'billing_visma', $user->ID ) ); ?>" class="regular-text" /><br />
            <span class="description"><?php _e("Visma Customer Number"); ?></span>
        </td>
    </tr>
    </table>
<?php }

add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {
    if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-user_' . $user_id ) ) {
        return;
    }
    
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false; 
    }
    update_user_meta( $user_id, 'billing_visma', $_POST['billing_visma'] );
}

以下是我通过 Order Adim 页面添加新客户资料元数据的方式:

add_action( 'woocommerce_admin_order_data_after_billing_address', 'customer_visma_edit' );
function customer_visma_edit( $order ){
    $value = get_user_meta( $order->get_customer_id(), 'billing_visma', true );
    ?>
    <div class="edit-address"><?php
        woocommerce_wp_text_input( array(
            'id' => 'billing_visma',
            'label' => __('<strong>Visma Customer Number:</strong>', 'woocommerce'),
            'placeholder' => '',
            'value' => $value,
            'wrapper_class' => 'form-field'
        ) );
    ?></div><?php
}


add_action('save_post_shop_order', 'customer_visma_save', 50, 3 );
function customer_visma_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_visma']) ) {
        $order = wc_get_order( $post_id );
        // Update order post meta data
        update_post_meta( $post_id, 'billing_visma', sanitize_text_field( $_POST['billing_visma'] ) );
        // Update user meta data
        update_user_meta( $order->get_customer_id(), 'billing_visma', sanitize_text_field( $_POST['billing_visma'] ) );
    }
}

标签: phpwordpresswoocommercemetadatauser-profile

解决方案


推荐阅读