Gift Option in WooCommerce: A Comprehensive Guide
In today’s e-commerce landscape, personalizing the shopping experience is key to enhancing customer satisfaction and driving sales. One effective way to do this is by offering a gift option in WooCommerce store. This article will walk you through the benefits of adding a gift option, explain the code implementation, and guide you on how to make the most of this feature for your store.
Why a Gift Option is Beneficial for You and Your Customers
Adding a gift option to your WooCommerce store is a win-win for both you and your customers. For customers, it provides a convenient way to send a personalized gift directly to someone special, complete with a custom message. This feature can significantly enhance the shopping experience, making it more likely that they will return to your store for future purchases.
For you as the store owner, offering a gift option opens up a new revenue stream by encouraging gift purchases, especially during holidays or special occasions. It can also increase the average order value when customers opt for the additional gift-wrapping service, which can be offered at an extra charge.
[Video Tutorial] How to add Gift option in WooCommerce.
Steps to add Gift option in WooCommerce
To implement this gift option functionality on your WooCommerce store, you can use the Code Snippets plugin. Here’s how to add the code step by step:
1. Install the Code Snippets Plugin
- Go to your WordPress dashboard.
- Navigate to Plugins > Add New.
- Search for Code Snippets.
- Click Install Now and then Activate.
2. Add a New Snippet for PHP Code
- Once the plugin is activated, go to Snippets > Add New.
- Enter a title for your snippet, like “Gift Option PHP“.
- Paste the code: In the code editor, paste the below code provided.
- After pasting the code, click Save Changes and Activate.
3. Add again a New Snippet for JavaScript code.
- Again go to Snippets > Add New.
- Enter a title for your snippet, like “Gift Option JS“.
- Paste the code: In the code editor, paste the below code provided.
- After pasting the code, click Save Changes and Activate.
Below are the PHP and JavaScript Codes
Below is the PHP Code.
// Add settings menu for gift options
add_action('admin_menu', 'add_gift_settings_menu');
function add_gift_settings_menu() {
add_submenu_page(
'woocommerce',
__('Gift Options', 'woocommerce'),
__('Gift Options', 'woocommerce'),
'manage_options',
'gift-options',
'gift_options_settings_page'
);
}
function gift_options_settings_page() {
?>
<div class="wrap">
<h1><?php esc_html_e('Gift Options Settings (by WPAMIT)', 'woocommerce'); ?></h1>
<form method="post" action="options.php">
<?php
settings_fields('gift_options_group');
do_settings_sections('gift-options');
submit_button();
?>
<!-- Support me section with a 20px margin above -->
<p style="font-size:18px; font-weight:bold; margin-top:20px; margin-bottom:20px;">
🙏Support me by ☕buy me a coffee <a href="https://buymeacoffee.com/wpamit">here</a>.
</p>
</form>
</div>
<?php
}
add_action('admin_init', 'register_gift_options_settings');
function register_gift_options_settings() {
register_setting('gift_options_group', 'gift_checkbox_text');
register_setting('gift_options_group', 'gift_charges_label');
register_setting('gift_options_group', 'gift_charges');
add_settings_section(
'gift_options_section',
__('Gift Option Settings', 'woocommerce'),
null,
'gift-options'
);
add_settings_field(
'gift_checkbox_text',
__('Gift Checkbox Text', 'woocommerce'),
'gift_checkbox_text_callback',
'gift-options',
'gift_options_section'
);
add_settings_field(
'gift_charges_label',
__('Gift Charges Label', 'woocommerce'),
'gift_charges_label_callback',
'gift-options',
'gift_options_section'
);
add_settings_field(
'gift_charges',
__('Gift Packing Charges', 'woocommerce'),
'gift_charges_callback',
'gift-options',
'gift_options_section'
);
}
function gift_checkbox_text_callback() {
$gift_checkbox_text = get_option('gift_checkbox_text', __('Is this a gift?', 'woocommerce'));
echo '<input type="text" name="gift_checkbox_text" value="' . esc_attr($gift_checkbox_text) . '" />';
}
function gift_charges_label_callback() {
$gift_charges_label = get_option('gift_charges_label', __('Gift Packing Charges', 'woocommerce'));
echo '<input type="text" name="gift_charges_label" value="' . esc_attr($gift_charges_label) . '" />';
}
function gift_charges_callback() {
$gift_charges = get_option('gift_charges', '5');
echo '<input type="number" step="0.01" name="gift_charges" value="' . esc_attr($gift_charges) . '" />';
}
add_action('woocommerce_before_add_to_cart_button', 'add_gift_option_to_product_page', 10);
function add_gift_option_to_product_page() {
global $product;
$product_id = $product->get_id();
$session = WC()->session;
$is_gift_checked = $session->get('is_gift_' . $product_id) ? 'checked' : '';
$gift_message = $session->get('gift_message_' . $product_id) ?: '';
$gift_checkbox_text = get_option('gift_checkbox_text', 'Is this a gift?');
$gift_charges_label = get_option('gift_charges_label', 'Gift Packing Charges');
$global_gift_charges = get_option('gift_charges', '5');
$product_gift_charges = get_post_meta($product_id, '_product_gift_charges', true);
$gift_charges = $product_gift_charges !== '' ? $product_gift_charges : $global_gift_charges;
echo '<div class="gift-option" style="margin-bottom:15px;">
<label><input type="checkbox" id="is_gift" name="is_gift" value="1" ' . $is_gift_checked . '> ' . esc_html($gift_checkbox_text) . ' (<strong>' . esc_html($gift_charges_label) . ': $' . esc_html($gift_charges) . '</strong>)</label>
<textarea id="gift_message" name="gift_message" placeholder="Add a message" style="display:' . ($is_gift_checked ? 'block' : 'none') . '; margin-top:10px;">' . esc_textarea($gift_message) . '</textarea>
</div>';
}
// Add product-level gift charges field in product edit page
add_action('woocommerce_product_options_shipping', 'add_gift_charges_product_field');
function add_gift_charges_product_field() {
woocommerce_wp_text_input(array(
'id' => '_product_gift_charges',
'label' => __('Gift Packing Charges', 'woocommerce'),
'desc_tip' => true,
'description' => __('Enter gift packing charges for this product. This will override the global gift charges.', 'woocommerce'),
'type' => 'number',
'custom_attributes' => array(
'step' => '0.01',
'min' => '0'
)
));
}
// Save the product-level gift charges field
add_action('woocommerce_process_product_meta', 'save_gift_charges_product_field');
function save_gift_charges_product_field($post_id) {
$gift_charges = sanitize_text_field($_POST['_product_gift_charges'] ?? '');
update_post_meta($post_id, '_product_gift_charges', $gift_charges);
}
// Add gift charges to the cart if the gift option is selected
add_action('woocommerce_cart_calculate_fees', 'apply_gift_charges');
function apply_gift_charges() {
foreach (WC()->cart->get_cart() as $cart_item) {
if (isset($cart_item['gift_message'])) {
$product_gift_charges = get_post_meta($cart_item['product_id'], '_product_gift_charges', true);
$gift_charges = $product_gift_charges !== '' ? $product_gift_charges : get_option('gift_charges', '5');
WC()->cart->add_fee(get_option('gift_charges_label', __('Gift Packing Charges', 'woocommerce')), $gift_charges);
break;
}
}
}
add_action('woocommerce_add_cart_item_data', 'save_gift_option_to_session', 10, 2);
function save_gift_option_to_session($cart_item_data, $product_id) {
$session = WC()->session;
if (!empty($_POST['is_gift'])) {
$gift_message = sanitize_text_field($_POST['gift_message']);
$session->set('is_gift_' . $product_id, true);
$session->set('gift_message_' . $product_id, $gift_message);
$cart_item_data['is_gift'] = true;
$cart_item_data['gift_message'] = $gift_message;
} else {
$session->__unset('is_gift_' . $product_id);
$session->__unset('gift_message_' . $product_id);
}
return $cart_item_data;
}
add_filter('woocommerce_get_cart_item_from_session', 'get_gift_option_from_cart_session', 20, 2);
function get_gift_option_from_cart_session($cart_item, $values) {
if (!empty($values['is_gift'])) {
$cart_item['is_gift'] = $values['is_gift'];
}
if (!empty($values['gift_message'])) {
$cart_item['gift_message'] = $values['gift_message'];
}
return $cart_item;
}
// Display 'Gift Message' in cart and checkout with edit icon
add_filter('woocommerce_get_item_data', 'display_gift_option_in_cart', 10, 2);
function display_gift_option_in_cart($item_data, $cart_item) {
if (!empty($cart_item['gift_message'])) {
$item_data[] = array(
'key' => __('Gift Message', 'woocommerce'),
'value' => '<p>' . esc_html($cart_item['gift_message']) . ' <span class="edit-icon" style="cursor:pointer; margin-left:10px;">✎</span></p>'
);
}
return $item_data;
}
// Save updated gift message to cart during checkout
add_action('woocommerce_cart_calculate_fees', 'update_gift_message_checkout', 10, 1);
function update_gift_message_checkout($cart) {
if (is_checkout() && !empty($_POST['edit_gift_message_checkout'])) {
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$cart_item['gift_message'] = sanitize_textarea_field($_POST['edit_gift_message_checkout']);
}
}
}
// Save gift message to order meta
add_action('woocommerce_checkout_create_order_line_item', 'save_gift_message_to_order_meta', 10, 4);
function save_gift_message_to_order_meta($item, $cart_item_key, $values, $order) {
if (!empty($values['gift_message'])) {
$item->add_meta_data(__('Gift Message', 'woocommerce'), sanitize_textarea_field($values['gift_message']), true);
}
}
// Handle AJAX request to update gift message
add_action('wp_ajax_update_gift_message', 'update_gift_message_callback');
add_action('wp_ajax_nopriv_update_gift_message', 'update_gift_message_callback');
function update_gift_message_callback() {
$updated_message = sanitize_text_field($_POST['gift_message'] ?? '');
if ($updated_message) {
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
WC()->cart->cart_contents[$cart_item_key]['gift_message'] = $updated_message;
}
WC()->cart->set_session();
WC()->cart->calculate_totals();
wp_send_json_success(array('message' => 'Gift message updated successfully.'));
} else {
wp_send_json_error(array('message' => 'No message provided.'));
}
wp_die();
}
Below is the JavaScript Code.
// JavaScript for showing/hiding the gift message textarea and edit icon functionality
add_action('wp_footer', function() {
?>
<script>
jQuery(document).ready(function ($) {
$('#is_gift').change(function () {
$('#gift_message').toggle(this.checked);
});
$(document).on('click', '.edit-icon', function () {
let currentMessage = $(this).parent().text().trim().replace('✎', '');
let newMessage = prompt('Edit your gift message:', currentMessage);
if (newMessage !== null) {
let $parent = $(this).parent();
$parent.html(newMessage + ' <span class="edit-icon" style="cursor:pointer; margin-left:10px;">✎</span>');
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
action: 'update_gift_message',
gift_message: newMessage,
},
success: function (response) {
alert(response.success ? 'Gift message updated successfully!' : 'Error: ' + response.data.message);
},
error: function () {
alert('An error occurred while saving the gift message.');
}
});
}
});
});
</script>
<?php
});
Code Explanation: Implementing the Gift Option
The provided code snippet allows you to add a comprehensive gift option feature to your WooCommerce store. This includes a settings page in the WordPress admin, where you can customize the text and charges associated with the gift option. The code also integrates this feature seamlessly into the product page, cart, and checkout process, allowing customers to add a gift message and pay additional charges for gift wrapping.
The code begins by adding a settings menu under the WooCommerce tab in the WordPress admin. This settings page includes fields where you can specify the text that appears next to the gift checkbox on the product page, as well as the label and default charges for the gift wrapping service. These settings are stored in the WordPress database and can be retrieved and displayed wherever necessary in your WooCommerce store.
Gift Option Settings Page: Features and Customization
The settings page added by the code is where you can customize the gift option feature. It allows you to:
- Gift Checkbox Text: This is the text that will appear next to the checkbox on the product page, prompting customers to choose the gift option.
- Gift Charges Label: This label will be displayed alongside the gift wrapping charges.
- Gift Packing Charges: Here, you can set the default amount customers will be charged for gift wrapping.
These settings can be easily adjusted through the WooCommerce settings submenu titled “Gift Options,” making it straightforward to modify the gift feature without touching the code.
Gift Charges Field on the Product Edit Page
One of the most powerful features of this code is the ability to specify gift packing charges on a per-product basis. Under the shipping tab of the product edit page, you’ll find a field labeled “Gift Packing Charges.” This field allows you to override the global gift charges for individual products, which is particularly useful if certain items require special packaging or handling.
By setting custom charges per product, you ensure that your pricing accurately reflects the cost associated with gift wrapping, which can vary depending on the product’s size, shape, or fragility.
How It Works: A Step-by-Step Process
- Product Page: When a customer views a product, they will see the gift option checkbox. If they select it, a text area will appear where they can add a personalized message.
- Cart Page: The gift message can be edited on the cart page. This ensures that customers can refine their message before proceeding to checkout.
- Checkout Page: The gift message remains editable during checkout, allowing customers to make last-minute changes. The gift wrapping charges, as set in the product edit page or globally, will be added to the order total.
- Order Placement: Once the customer places the order, the gift message will be saved and displayed on the thank you page, giving them confirmation that their gift message has been successfully recorded.
Displaying the Gift Message on the Cart Page and Checkout Page
Customer can check and also edit the Gift message on both cart and checkout page. To edit the gift message, customer is just need to click on edit icon which is after the gift message.
Viewing the Gift Message in the Customer’s Order Page
Customers can view their gift message in the order details section of their account. This ensures that they have a record of the message they sent along with the gift, which can be particularly useful for future reference.
Admin View: Gift Message on the Order Edit Page
As the store administrator, you’ll have access to the gift message from the order edit page in the WordPress admin panel. This visibility is crucial for ensuring that the correct message is included with the gift, and it allows you to manage the packaging process efficiently.
Conclusion
Adding a gift option to your WooCommerce store is an excellent way to enhance the customer experience and increase your revenue. The provided code not only makes this feature possible but also offers extensive customization options to tailor the gift service to your store’s needs. By following this guide, you can implement the gift option feature seamlessly, providing your customers with an added layer of personalization and convenience.