
Change Custom Add to Cart button to Sold Out text if product is sold out.
Elementor Pro has a Custom Add To Cart button widget but it does not change when the product is sold out. Instead, it send the user to the product page where they then see it is sold out. This is not a good user experience. My code changes the button to text in that situation.
Use case
One of my clients has education books where some have small blemishes, aka ‘seconds’. These limited numbers are offered at a discount.
Unlike the regular, blemish free books where we do not manage the stock levels in WooCommerce, only a small number of these ‘seconds’ are available so stock has to be managed.
Instead of using WooCommerce product and product archive pages, the site uses regular pages with the Custom Add To Cart buttons. For products without stock management this works well but when these ‘seconds’ sell out it’s not good and customer satisfaction is impacted.
Do stock check before displaying button
As I did in two other blog posts, Conditionally show an Elementor section and Remove markup of hidden element, I am using the elementor/widget/render_content
filter.
As this filter is called before each widget is rendered, it is important to be as efficient as possible.
Firstly, the code does not change the widget output when in the admin area, hence the is_admin()
check at the start. The it compares the widget name to see if it is 'wc-add-to-cart'
, the Custom Add to Cart button widget.
After that the main part of this short function retrieves the product ID from the widget settings, creates a product object and checks whether it is in stock. If not, then it returns markup where the button is replaced with 'Sold Out'
text.
For flexibility, the 'Sold Out'
text is passed through a filter. This will allow users easily change the text without changing the plugin code. I have included an example of this filter at the bottom of the plugin.
Screenshots
This shows the Add to Cart button (we change the button text on my client’s site) when the product is in stock.
Then, when the product is sold out, the button is replaced with ‘SOLD OUT’ text.
Make it an option in Elementor Pro
It would be more efficient if this code was incorporated into the Elementor widget. I contacted Elementor Support, asking how to submit an enhancement request. I was planning to submit a pull request instead of asking them to develop the code.
I said I didn’t have an Elementor Pro license, that my client did. They repeatedly asked for my license so I gave up.
Leave a Reply