Reputation: 552
I developed a custom Product page where I have to place the form with the Name field and Email address field. When I click a Purchase button Woocommerce links me to the Checkout Page (I avoided the Cart page). How can enter name and email on the Product page and keep the input data on the Checkout page? I broke my head trying to find an appropriate solution, but unfortunately can't get how I can do that. Much appreciate any help!
Upvotes: 0
Views: 638
Reputation:
You can use "woocommerce_add_cart_item_data", "woocommerce_get_item_data", "woocommerce_checkout_create_order_line_item" hooks.
function my_add_item_data($cart_item_data, $product_id, $variation_id)
{
if(isset($_REQUEST['user_name']) && $_REQUEST['user_name'] != ""){
$cart_item_data['user_name'] = sanitize_text_field($_REQUEST['user_name']);
}
if (isset($_REQUEST['user_email']) && $_REQUEST['user_email'] != "" ){
$cart_item_data['user_email'] = sanitize_text_field($_REQUEST['user_email']);
}
return $cart_item_data;
}
add_filter('woocommerce_add_cart_item_data', 'my_add_item_data' ,10,3);
function my_add_item_meta($item_data, $cart_item)
{
if(array_key_exists('user_name', $cart_item))
{
$user_name = $cart_item['user_name'];
$item_data[] = array(
'key' => 'User Name',
'value' => $user_name
);
}
if(array_key_exists('user_email', $cart_item))
{
$user_email= $cart_item['user_email'];
$item_data[] = array(
'key' => 'User Email',
'value' => $user_email
);
}
return $item_data;
}
add_filter('woocommerce_get_item_data', 'my_add_item_meta', 10, 2);
function my_add_custom_order_line_item_meta($item, $cart_item_key, $values, $order)
{
if(array_key_exists('user_name', $values))
{
$user_name = $values['user_name'];
$item->add_meta_data( 'User Name', $user_name );
}
if(array_key_exists('user_email', $values))
{
$user_email= $values['user_email'];
$item->add_meta_data( 'User Email', $user_email);
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'my_add_custom_order_line_item_meta', 10, 4 );
Updated:
Please refer following guide, https://businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/
You can print input fields what you want to put in specific position.
For example, use woocommerce_before_add_to_cart_button action to put your input fields before "Add to Cart" button.
function my_before_add_to_cart_button(){
echo '<input type="text" name="user_name" placeholder="" value=""/>';
echo '<input type="text" name="user_email" placeholder="" value=""/>';
}
add_action('woocommerce_before_add_to_cart_button', 'my_before_add_to_cart_button');
Upvotes: 1