A client of mine asked me to code a checkbox on the single product page called “Is this a gift?”. They noticed that their customers who want to gift the product to a friend get confused with the “Shipping to a different address” form in the WooCommerce checkout.

So, what about renaming “Shipping to a different address” into “Who is this gift for?” if a “gift” is in the cart? Well, this snippet does just that and you can adapt it / customize it to your specific case.

“Is this a gift?” checkbox @ WooCommerce single product page

PHP Snippet: “Is This a Gift?” Checkbox @ Single Product Page – WooCommerce


/**
* @snippet       "Is This a Gift?" Checkbox @ Single Product Page - WooCommerce
* @how-to        Get CustomizeWoo.com FREE
* @sourcecode    https://businessbloomer.com/?p=73381
* @author        Rodolfo Melogli
* @testedwith    WooCommerce 3.5.1
* @donate $9     https://businessbloomer.com/bloomer-armada/
*/

// -------------------------
// 1. Display Is this a Gift checkbox 
 
add_action( 'woocommerce_before_add_to_cart_quantity', 'bbloomer_is_this_gift_add_cart', 35 );
 
function bbloomer_is_this_gift_add_cart() {
		
		?>

		<p class="">
		<label class="checkbox">
		<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="is-gift" id="is-gift" value="Yes"><span>Is this a gift?</span>
		</label>
		</p>

		<?php

}
 
// -------------------------
// 2. Add the custom field to $cart_item
 
add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_store_gift', 10, 2 );
 
function bbloomer_store_gift( $cart_item, $product_id ) {
if( isset( $_POST['is-gift'] ) && $_POST['is-gift'] == "Yes" ) {
	$cart_item['is-gift'] = $_POST['is-gift'];
}
return $cart_item; 
}
 
// -------------------------
// 3. Preserve the custom field in the session
 
add_filter( 'woocommerce_get_cart_item_from_session', 'bbloomer_get_cart_items_from_session', 10, 2 );
 
function bbloomer_get_cart_items_from_session( $cart_item, $values ) {
if ( isset( $values['is-gift'] ) ){
	$cart_item['is-gift'] = $values['is-gift'];
}
return $cart_item;
}
 
// -------------------------
// 4. If gift in cart, edit checkout behavior:
// a) open shipping by default
// b) rename shipping title
 
add_action ( 'woocommerce_before_checkout_form', 'bbloomer_gift_checkout' );

function bbloomer_gift_checkout() {
	
	$itsagift = false;
	
	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		if ( isset( $cart_item['is-gift'] ) ) {
			$itsagift = true;
			break;
		}
	}
	
	if ( $itsagift == true ) {
		add_filter( 'woocommerce_ship_to_different_address_checked', '__return_true' );
		add_filter( 'gettext', 'bbloomer_translate_shipping_gift' );
	}
	
}

function bbloomer_translate_shipping_gift( $translated ) {
$translated = str_ireplace( 'Ship to a different address?', 'Who is this Gift For?', $translated );
return $translated;
}

Share:

Leave a Reply