In this tutorial, I will show you how to show a nice popup when user cart contains products from specific categories.
Let’s start by defining two constants that will hold some values for us that can easily be changed whenever needed.
Define Necessary Constants
/** ** ** I like to prefix my functions, constants and ** variables in global scope ** with YMCODE_/ymcode_ to prevent collision. ** Feel free to change it. **/ /** ** Set your custom message. Do not include html ** as it will be stripped off. **/ define('YMCODE_CUSTOM_MESSAGE', 'You have a special discount'); /** ** Set one or more categories IDs in the array. **/ define('YMCODE_CAT_IDS', [1,2, ]);
Lets write the function that will echo the message to the users.
Function to check if the cart has products from given categories
The function below will run via a hook when users visit the cart page. It will check if the products in the cart are from specific categories and if so, will hook the function to show the popup.
Hook the function to check for product categories
Almost done! We just need to hook the above function to run on cart page.
Download the complete, formatted code from github gists.
How to use the code
Well, in case, you are not a developer and wondering where to copy the code, download the complete code from github gist, embedded above. Then change the contestants at the top and place them at the end of your active theme’s functions.php