I want to include a link to a profile of the current user who submitted a checkout form through WooCommerce.
That is, to place automatically a current user’s author link like this in the hidden field: example.com/author/username
I want to achieve this by adding a hidden field in checkout form. So to get a link I would write something likes this:
<?php
$currentUser = get_current_user_id();
$user = get_user_by( 'id', $currentUser );
$userUrl = get_bloginfo( 'home' ) . '/author/' . $user->user_login;
echo $userUrl;
?>
My question is how can I create this type of hidden field in checkout form?
With a custom function hooked in woocommerce_after_order_notes
action hook, you can also directly output a hidden field with this user "author link" as a hidden value, that will be submitted at the same time with all checkout fields when customer will place the order.
Here is that code:
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_hidden_field', 10, 1 );
function my_custom_checkout_hidden_field( $checkout ) {
// Get an instance of the current user object
$user = wp_get_current_user();
// The user link
$user_link = home_url( '/author/' . $user->user_login );
// Output the hidden link
echo '<div id="user_link_hidden_checkout_field">
<input type="hidden" class="input-hidden" name="user_link" id="user_link" value="' . $user_link . '">
</div>';
}
Then you will need to save this hidden field in the order, this way:
add_action( 'woocommerce_checkout_update_order_meta', 'save_custom_checkout_hidden_field', 10, 1 );
function save_custom_checkout_hidden_field( $order_id ) {
if ( ! empty( $_POST['user_link'] ) )
update_post_meta( $order_id, '_user_link', sanitize_text_field( $_POST['user_link'] ) );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and working