我正在建设一个Woocommerce网站,我想将用户的生日添加到数据库中的usermeta,并在wp-admin下的个人资料中显示。但是,我对PHP的了解有限。
我已经从Woocommerce文档中获取了这里的信息来在结帐时显示它,并且它的显示是正确的。
Woocommerce文档向您展示如何将其添加到订单信息中,但不是添加到用户账户本身。 它已正确地添加到订单,但未添加到账户中。
以下是我目前的进展:
我尝试了这个替代方案来更新用户元数据,而不是用我的版本。
我已经从Woocommerce文档中获取了这里的信息来在结帐时显示它,并且它的显示是正确的。
Woocommerce文档向您展示如何将其添加到订单信息中,但不是添加到用户账户本身。 它已正确地添加到订单,但未添加到账户中。
以下是我目前的进展:
/**
* Add the field to the checkout
*/
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field">';
woocommerce_form_field( 'birthdate', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Date of Birth'),
'placeholder' => __('mm/dd/yyyy'),
), $checkout->get_value( 'birthdate' ));
echo '</div>';
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['birthdate'] )
wc_add_notice( __( 'Please enter your date of birth.' ), 'error' );
}
/**
* update order meta with field value
*/
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['birthdate'] ) ) {
update_post_meta( $order_id, 'Birthdate', sanitize_text_field( $_POST['birthdate'] ) );
}
}
/**
* update user meta with birthdate
*/
add_action ( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action ( 'edit_user_profile_update', 'my_save_extra_profile_fields' );
function my_save_extra_profile_fields( $user_id )
{
if ( ! empty( $_POST['birthdate'] ) ) {
update_usermeta( $user_id, 'Birthdate', sanitize_text_field( $_POST['birthdate'] ) );
}
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
add_action ( 'show_user_profile', 'my_custom_checkout_field_display_admin_order_meta' );
add_action ( 'edit_user_profile', 'my_custom_checkout_field_display_admin_order_meta' );
function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Birthdate').':</strong> ' . get_post_meta( $order->id, 'Birthdate', true ) . '</p>';
}
我在用户信息页面也遇到了这个错误:
Notice: WP_User->id was called with an argument that is deprecated since
version 2.1.0! Use WP_User->ID instead. in
/Applications/MAMP/htdocs/tst_dev/wp-includes/functions.php on line 3891
我尝试了这个替代方案来更新用户元数据,而不是用我的版本。
add_action( 'user_register', 'my_custom_update_user');
function my_custom_update_user( $user_id )
{
if ( $user_id != 0 ) { // check if user is not a guest
update_usermeta( $user_id, 'Birthdate', sanitize_text_field( $_POST['birthdate'] ) );
}
}