Development

How to add a button under the Add to Cart button in Woocommerce

Perhaps you need to give the user another option such as a page with a form

7 months ago | The Author, Charlie Cooper by Charlie Cooper

Sometimes, you might have another page that you want the user to go to instead of adding an item to their cart. For example, if you have a website selling mobile phones you may have a page for trade-ins.

We’re going to use PHP to add a second button underneath the woocommerce add to cart button across all products. We’ll then look at only showing the button on specific category.

There is some coding involved, but it’s not as complicated as you may think. If you have the snippets plugin it’s even simpler.

Knowledge of CSS will be handy when you want to change how it looks.

Let’s dive in. If you have the snippets plugin, start a new snippet and skip to step 3.

1.Open the Theme File Editor

First, you’re going to need access to functions.php in your root of your theme. You can access this by going to ‘Appearance > Theme File Editor’ from your WordPress backend.

2.Open functions.php

Once on the theme file editor page, look on the right of the page where all the file names are and find functions.php. Click it to view the contents.

3.Paste in the PHP action and function

Now scroll right to the bottom of the file and if you can see ?> at the end of the file, simply remove it (it doesn’t need to be there).

If it’s not there you’re ready to continue. Now paste in the code below, and hit ‘Update File’.

Note: you’ll need to adjust the button text and button link text before updating
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button' );
 
function add_custom_button() {
   echo '<a href="button-link" class="button alt">Button Text</a>';
}

There – all done!

But what if you want to only show the button in a specific scenario? Let’s say we only want the button to show if the product is in a category called ‘Pixel’.

We need to update our code to only output the button when the product is in the category we’ve specified. Follow on from the steps above.

1. Update the code

Change the code we used earlier to this and hit save:

Note: You’ll need to edit the code replacing ‘pixel’ with the category you’re using and adjust the button text and button link text before saving.

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button_if_pixel_category' );
 
function add_custom_button_if_pixel_category() {
   global $product;
   if ( has_term( 'pixel', 'product_cat', $product->get_id() ) ) {
      echo '<a href="button link" class="button alt">Button Text</a>';
   }
}
Get in touch today
Great Pricing
Unique Websites
Get found on Google