I am using woocommerce with Wordpress and have added some custom fields to the checkout:
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
$extra_fields = array('job_title', 'company', 'telephone', 'occupation');
foreach($extra_fields as $key => $value) {
woocommerce_form_field($value, array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __($label),
'value' => '',
), $checkout->get_value( $value ));
}
}
Now currently, these appear in the checkout fine, not sure if using woocommerce_after_order_notes is right in this case. I have also added some custom fields to the user meta that correspond to the fields added to the checkout - which all display in the user profile page:
function add_contact_methods( $contactmethods ) {
$contactmethods['job_title'] = 'Job Title';
$contactmethods['company'] = 'Company Name';
$contactmethods['telephone'] = 'Telephone';
$contactmethods['occupation'] = 'Occupation';
$contactmethods['refer'] = 'How you heard about us?';
return $contactmethods;
}
add_filter('user_contactmethods','add_contact_methods',10,1);
As you can imagine, if I update any of these field in any profile page, it works fine but what I cant seem to do is update the user meta when a new user makes a purchase, it does not update the user meta for these fields in the database.
I understand alot of how this works, and understand that I must hook into a Woocommerce process to add the fields into the process. So I have added this code into my functions too:
add_action('woocommerce_checkout_update_user_meta', 'my_custom_checkout_field_update_user_meta');
function my_custom_checkout_field_update_user_meta( $user_id ) {
global $extra_fields;
foreach($extra_fields as $key => $value) {
if ($_POST[$value]) update_user_meta( $user_id, $value, esc_attr($_POST[$value]));
}
}
Now the twist is, this works if a user who is already signed in as a member, makes a repurchase and goes through the checkout - the reason this works is because $user_id already exists, but when a new user is checking out, they do not yet exist as a user, hence the function cannot update the user meta of NIL where $user_id does not exist.
My question is, how do I hook into the checkout process, presumably AFTER the user has been created, so I that I can get the $user_id returned, and execute this function to update the user meta.
class-wc-checkout.php line 639 creates the new user with $this->customer_id = wp_insert_user( apply_filters( 'woocommerce_new_customer_data', $new_customer_data ) ); The new customer data is an array listed just above that line.
Following that, you can access the user id with line 649's action do_action( 'woocommerce_created_customer', $this->customer_id );
It is unlikey, in your case, you will need to use the filter, but simply add the action 'woocommerce_created_customer', pull in the id, and add the meta.
When customer is not logged in checkout page should be acceptable field customer want to create a new account.Below sample code change in checkout page when customer order a new item and update user meta data.
function user_extra_meta_fields(){
return array(
'job_title' => __( 'Job Title', 'yourtext_domain'),
'company' => __( 'Company Name', 'yourtext_domain'),
'telephone' => __( 'Telephone', 'yourtext_domain'),
'occupation' => __( 'Occupation', 'yourtext_domain'),
'refer' => __( 'How you heard about us?', 'yourtext_domain'),
);
}
function add_contact_methods( $contactmethods ) {
$contactmethods = array_merge( $contactmethods, user_extra_meta_fields());
return $contactmethods;
}
add_filter('user_contactmethods','add_contact_methods',10,1);
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
foreach( user_extra_meta_fields() as $name => $label) {
$value = '';
if( is_user_logged_in() )
$value = get_user_meta( get_current_user_id(), $name, true );
woocommerce_form_field( $name, array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => $label,
), $value );
}
}
add_action( 'woocommerce_checkout_process', 'user_fields_woocommerce_checkout_process' );
function user_fields_woocommerce_checkout_process(){
if( is_user_logged_in() )
add_action('woocommerce_checkout_update_user_meta', 'my_custom_checkout_field_update_user_meta' );
else
add_action( 'woocommerce_created_customer', 'my_custom_checkout_field_update_user_meta' );
}
function my_custom_checkout_field_update_user_meta( $user_id ) {
foreach( array_keys( user_extra_meta_fields() ) as $meta_name ){
if( isset( $_POST[$meta_name] ) ){
$meta_value = $_POST[$meta_name] ? esc_attr($_POST[$meta_name]) : '';
update_user_meta( $user_id, $meta_name, $meta_value );
}
}
}
// if want to validate field
add_action( 'woocommerce_after_checkout_validation', 'user_fields_woocommerce_after_checkout_validation' );
function user_fields_woocommerce_after_checkout_validation( $posted ){
$validate = true;
if( ! is_user_logged_in() && empty( $posted['createaccount'] ) )
$validate = false;
if( $validate == false )
return;
$meta_data = user_extra_meta_fields();
foreach( array_keys( $meta_data ) as $meta_name ){
if( empty($_POST[$meta_name]) )
wc_add_notice( sprintf( __(' <strong>%s</strong> is required.', 'yourtext_domain'), $meta_data[$meta_name] ), 'error' );
}
}
Related
When user completes the order, I want to save the user selected value as user registration date. I know it can be achived with this code:
wp_update_user(
[
'ID' => $user_id,
'user_registered' => $user->user_registered,
]
);
But how I can make it work with the rest of my code? How I can save this data as the registration date? I know how to save the order meta etc. but I've never did something like this.
add_action( 'woocommerce_before_checkout_registration_form', 'custom_checkout_fields_before_billing_details', 20 );
function custom_checkout_fields_before_billing_details(){
$domain = 'woocommerce';
$checkout = WC()->checkout;
echo '<div id="custom_checkout_field">';
woocommerce_form_field( '_custom_field_name', array(
'type' => 'text',
'label' => __('SELECT DATE', $domain ),
'placeholder' => __('DATE"', $domain ),
'class' => array('custom-field-class form-row-wide'),
'required' => false, // or false
), $checkout->get_value( '_custom_field_name' ) );
echo '</div>';
echo '<script>jQuery(document).ready(function( $ ) {$( "#_custom_field_name").datepicker();});</script>';
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if( isset($_POST['_custom_field_name']) && ! empty($_POST['_custom_field_name']) )
$order->update_meta_data( '_custom_field_name', sanitize_text_field( $_POST['_custom_field_name'] ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_datepicker' );
function enqueue_datepicker() {
if ( is_checkout() ) {
// Load the datepicker script (pre-registered in WordPress).
wp_enqueue_script( 'jquery-ui-datepicker' );
// You need styling for the date picker. For simplicity, I've linked to Google's hosted jQuery UI CSS.
wp_register_style( 'jquery-ui', '//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css' );
wp_enqueue_style( 'jquery-ui' );
}
}
I need a custom fields on the inventory tab that will be filled in with the zipcode as the location of the agent.
Armed with the references I got here, now I have that field.
what I want to ask is how to concatenate this meta data with woocommerce shortcode?
I think like :
['products limit="12" columns="4" zipcode="12345"]
where "12345" will be changing dynamically as needed (zipcode filled based on agent location).
I have tried to do something but it is not working properly.
Here's the full code.
function action_woocommerce_product_options_inventory_product_data_zipcode() {
woocommerce_wp_text_input( array(
'id' => '_zipcode',
'label' => __( 'Zipcode', 'woocommerce' ),
'description' => __( 'Please fill your zipcode.', 'woocommerce' ),
'desc_tip' => 'true',
'placeholder' => __( '12345', 'woocommerce' )
) );
}
add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_product_options_inventory_product_data_zipcode' );
// Save zipcode
function action_woocommerce_admin_process_product_object_zipcode( $product ) {
// Isset
if ( isset( $_POST['_zipcode'] ) ) {
// Update
$product->update_meta_data( '_zipcode', sanitize_text_field( $_POST['_zipcode'] ));
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object_zipcode', 10, 1 );
Try put to shortcode products :
function filter_shortcode_atts_products_zipcode ( $out, $pairs, $atts, $shortcode) {
if ( isset ( $atts['zipcode'] ) && !empty($atts['zipcode']) ) {
$out['zipcode'] = true;
} else {
$out['zipcode'] = false;
}
return $out;
}
add_filter( 'shortcode_atts_products', 'filter_shortcode_atts_products_zipcode', 10, 4);
function filter_woocommerce_shortcode_products_query_zipcode( $query_args, $atts, $type) {
if ( $type == 'products' && $atts['zipcode'] ) {
// Meta query
$query_args['meta_query'] = array(
array(
'key' => '_zipcode',
'value' => $atts['zipcode'],
'compare' => 'LIKE',
)
);
}
return $query_args;
}
add_filter( 'woocommerce_shortcode_products_query', 'filter_woocommerce_shortcode_products_query_zipcode', 10, 3 );
On testing I tried :
['products limit="12" columns="4" zipcode="12345"]
shortcode has displayed the product but does not refer to the postal code in the short code ("12345") but to all products that have a postal code.
Can somebody help me?
Thank you
Something doesn't feel right about the shortcode attribute function. I think you're setting the attribute as true and therefore it's comparing anything "truthy." Maybe just try setting the true one as the zipcode, like this:
function filter_shortcode_atts_products_zipcode ( $out, $pairs, $atts, $shortcode) {
if ( isset ( $atts['zipcode'] ) && !empty($atts['zipcode']) ) {
$out['zipcode'] = $atts['zipcode'];
} else {
$out['zipcode'] = false;
}
return $out;
}
That way it'll return the zipcode if it exists, and false if it doesn't, which the query can then use for the comparison.
I have created a custom checkout select field with validation. I was able to show this field in the order in the backend and in the confirmation email. I added it with this code:
/*** ADD DOCKING STATION FIELD # WC CHECKOUT ***/
add_action( 'woocommerce_after_checkout_billing_form', 'bbloomer_add_custom_checkout_field' );
function bbloomer_add_custom_checkout_field( $checkout ) {
$current_user = wp_get_current_user();
$saved_docking_station = $current_user->docking_station;
woocommerce_form_field( 'docking_station', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => 'Do you have a docking station/ loading dock on-site?',
'required' => true,
'default' => $saved_docking_station,
'options' => array(
'' => __( 'Choose an option' ),
'No' => __( 'No' ),
'Yes' => __( 'Yes' ),
)
), $checkout->get_value( 'docking_station' ) );
}
/* Validate this field */
add_action( 'woocommerce_checkout_process', 'bbloomer_validate_new_checkout_field' );
function bbloomer_validate_new_checkout_field() {
if ( ! $_POST['docking_station'] ) {
wc_add_notice( '<strong>Docking station</strong> is a required field.', 'error' );
}
}
/* Save & show this field # WC orders & emails */
add_action( 'woocommerce_checkout_update_order_meta', 'bbloomer_save_new_checkout_field' );
function bbloomer_save_new_checkout_field( $order_id ) {
if ( $_POST['docking_station'] ) update_post_meta( $order_id, '_docking_station', esc_attr( $_POST['docking_station'] ) );
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'bbloomer_show_new_checkout_field_order', 10, 1 );
function bbloomer_show_new_checkout_field_order( $order ) {
$order_id = $order->get_id();
if ( get_post_meta( $order_id, '_docking_station', true ) ) echo '<p><strong>Docking station:</strong> ' . get_post_meta( $order_id, '_docking_station', true ) . '</p>';
}
add_action( 'woocommerce_email_after_order_table', 'bbloomer_show_new_checkout_field_emails', 20, 4 );
function bbloomer_show_new_checkout_field_emails( $order, $sent_to_admin, $plain_text, $email ) {
if ( get_post_meta( $order->get_id(), '_docking_station', true ) ) echo '<p><strong>Docking station:</strong> ' . get_post_meta( $order->get_id(), '_docking_station', true ) . '</p>';
}
I also want to show this field on the account page; in the tab Account details (/my-account/edit-account). It would be perfect if the value of the docking field is visible on the account page and that the users can change this value on the account page for future orders.
I wonder if it's even possible to show the exact same field on the account page? I can imagine that this is not possible because checkout fields and account (user) fields are different type of fields and therefore you can't use the same field for both purposes. However, I hope it's possible.
I'm trying to update a custom product meta box field using the updating system from WooCommerce core. Here is my code:
The new field Shipping info
add_action( 'woocommerce_product_options_shipping', 'my_product_options_shipping' );
function my_product_options_shipping() {
global $post;
$shipping_info = get_post_meta( $post->ID, '_shipping_info', true );
woocommerce_wp_text_input(
array(
'id' => '_shipping_info',
'value' => $shipping_info,
'label' => __( 'Shipping info', 'woocommerce' ),
'placeholder' => __( 'Shipping in two days', 'woocommerce' ),
)
);
}
And this is the function that adds the new field as prop in WC_Meta_Box_Product_Data::save
add_action( 'woocommerce_admin_process_product_object', 'my_admin_process_product_object' );
function my_admin_process_product_object( $product ) {
$product->set_props(
array(
'shipping_info' => isset( $_POST['_shipping_info'] ) ? wc_clean( wp_unslash( $_POST['_shipping_info'] ) ) : null,
)
);
}
I think I'm missing a step. Shouldn't it be saved automatically from function WC_Meta_Box_Product_Data::save which is attached to woocommerce_process_product_meta?
EDIT
I found the missing step. I need to add my custom post meta in the protected array $extra_data from abstract class WC_Data.
I'm not too good at OOP, so how I can access that array to push my custom data?
I can see you're just doing $shipping_info = get_post_meta( $post->ID, '_shipping_info', true );
So why not save the trouble and just use update_post_meta
add_action( 'woocommerce_admin_process_product_object', 'my_admin_process_product_object' );
function my_admin_process_product_object( $product ) {
update_post_meta($product->get_id(), '_shipping_info', wc_clean( wp_unslash( $_POST['_shipping_info'] ) ) );
}
I am trying to display the "billing_gender" custom field I have added to my checkout form to the customer new account notification email.
The field is correctly saved to the database but it is shown empty in the new account email.
Other user meta fields (phone, ...) work but not my custom checkout field.
I guess it is saved to late in the user meta information but I really can't figure it out :
Here is my code :
functions.php
add_filter( 'woocommerce_checkout_fields' , 'divi_override_checkout_fields' );
function divi_override_checkout_fields( $fields ) {
unset($fields['billing']['billing_company']);
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_address_2']);
unset($fields['billing']['billing_city']);
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_state']);
unset($fields['billing']['billing_country']);
// Custom gender field
$fields['billing']['billing_gender'] = array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Title', 'divi-ultimate'),
'required' => true,
'priority' => 3,
'options' => array(
'' => __( 'Select title', 'divi-ultimate' ),
'male' => __( 'Mr', 'divi-ultimate' ),
'female' => __( 'Mrs', 'divi-ultimate' )
),
);
return $fields;
}
// Gender select default value
add_filter( 'default_checkout_billing_gender', 'checkout_billing_gender',10,2 );
function checkout_billing_gender($value) {
if ( is_user_logged_in()){
$current_user = wp_get_current_user();
$value = get_user_meta( $current_user->ID, 'billing_gender', true );
}
return $value;
}
//* Update the order meta with fields values
add_action('woocommerce_checkout_update_order_meta', 'divi_select_checkout_field_update_order_meta', 10, 2);
function divi_select_checkout_field_update_order_meta( $order_id ) {
if ($_POST['delivery-shop']) update_post_meta( $order_id, 'delivery-shop', esc_attr($_POST['delivery-shop']));
if ($_POST['billing_gender']) update_post_meta( $order_id, 'billing_gender', esc_attr($_POST['billing_gender']));
}
//* Update the user meta with gender value
add_action( 'woocommerce_checkout_update_user_meta', 'divi_save_extra_user_fields', 10, 2 );
function divi_save_extra_user_fields($customer_id) {
if (isset($_POST['billing_gender'])) {
update_user_meta( $customer_id, 'billing_gender', esc_attr($_POST['billing_gender']) );
}
}
What am I doing wrong ?
Cheers.
Here is the customer-new-account.php file :
$user = get_user_by('login', $user_login );
if (!empty($user)) {
$gender = get_user_meta($user->ID, 'billing_gender', true);
$lastname = $user->last_name;
$user_email = $user->user_email;
}
if( !empty($gender) && !empty($lastname) ) {
printf( esc_html__( 'Dear ' . $gender . ' %s,', 'woocommerce' ), esc_html( $lastname ) );
}
else {
printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $email ) );
} ?>