Add Custom Message to Empty Cart in WooCommerce
Explanation
If you're looking to add a personal touch to your WooCommerce store, you can customize the message that appears when a customer's cart is empty. This can encourage them to continue shopping or highlight special promotions.
Here's a simple way to do it:
- First, ensure WooCommerce is active on your site. The code checks for this before doing anything else.
- When the cart is empty, a custom message will appear. In this example, the message says: "Your cart is currently empty. Browse our products and add them to your cart!"
- This message is displayed using a WooCommerce function that shows notices on the cart page.
To make this work, the code hooks into WooCommerce's system using an action. This means it automatically runs at the right time, specifically when the cart is empty.
Feel free to change the message text to suit your store's tone and style. Just replace the text inside the quotation marks with your own message.
Code
<?php
// Add a custom message to the WooCommerce empty cart page
function wp_dudecom_custom_empty_cart_message() {
// Check if WooCommerce is active
if ( function_exists( 'is_cart' ) && is_cart() && WC()->cart->is_empty() ) {
// Custom message to display when the cart is empty
$custom_message = __( 'Your cart is currently empty. Browse our products and add them to your cart!', 'text-domain' );
// Display the custom message
wc_print_notice( $custom_message, 'notice' );
}
}
add_action( 'woocommerce_cart_is_empty', 'wp_dudecom_custom_empty_cart_message' );
?>
Instructions
File Location: Add the following code to your theme's functions.php
file or a custom plugin file.
Prerequisites:
- Ensure WooCommerce is installed and activated on your WordPress site.
Implementation Steps:
- Access your WordPress admin dashboard.
- Navigate to Appearance > Theme Editor if you are adding the code to
functions.php
. Alternatively, use a code editor if you are adding it to a custom plugin file. - Locate and open the
functions.php
file of your active theme or your custom plugin file. - Copy and paste the provided code snippet into the file.
- Save the changes to the file.
- Visit your WooCommerce cart page to verify that the custom message appears when the cart is empty.
Note: You can customize the message by editing the text within the quotation marks in the $custom_message
variable.
If you need assistance with implementation or require more advanced functionality, consider reaching out to wp-dude.com for expert help.