Discover in this tutorial how to display an add to cart button on a CPT post that you sell using WooCommerce.
If you are using a Custom Post Type (CPT), such as workshops or courses, but you want to sell them using WooCommerce, you may want to give the option to the potential customer to add the product directly from the CPT entry.
So in this tutorial you are going to learn how to relate a CPT to a WooCommerce product and how you can display a button to add it to the cart.
Steps to display an add to cart button in WordPress
1. Create a custom relationship field with ACF
If you haven’t already, download and install the Advanced Custom Fields plugin. The free version from WordPress repository is sufficient in this case.
Once activated, go to Custom Fields > Add New and create a relationship field.
Once you have created and configured the custom field, indicate in Location > Rules that you want to be displayed in the post type of workshop, course or the CPT you want to relate to a WooCommerce product.
2. Select the WooCommerce product related to your CPT
Next, the idea is for you to relate your CPT (workshop, course…) to the WooCommerce product you have created to sell it.
To do this, edit the entry of your CTP and go to the “Related” metabox, below the content, and select the WooCommerce product.
3. Create the shortcode
Add the following code at the end of functions.php or in your functionality plugin:
With this code you create a shortcode that allows you to display an add to cart button using the shortcode
[buy_button text="x" class="y
"]. Where you can replace “x” with the text you want to display on the button, and “y” to add a custom CSS class.
4. Insert the shortcode wherever you want
The advantage of shortcodes is that you can insert them anywhere on the web.
You only have to use the shortcode by defining the “class” and “text” attributes where you want it to be displayed.
For example, imagine that you have created a workshop CPT where you want to add a buy button with the text “Buy” and that it has the CSS class “workshop”. This would be the shortcode you would use to display it:
[buy_button text="Buy" class="workshop"].
Now you know how to display an add to cart button, in which you can customize the text displayed and its layout.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂