A step-by-step demo to find the appropriate WooCommerce hook to add new code to - without modifying a template file.
When working with WooCommerce much of the initial work is finding the appropriate hook to attach your code to or template file to modify.
In this post I detail the steps I took to add a second “Proceed to Checkout” link above the cart contents on the Cart page. I always aim to implement my changes without modifying a WooCommerce template file.
The first step is to search for some text that is on the page that you want to change.
Finding Proceed to Checkout
I use Total Commander as my file manager. It has a convenient search facility. With this I quickly find the ‘Proceed to Checkout‘ text in templates/cart/proceed-to-checkout-button.php. I then searched for the filename (proceed-to-checkout-button.php) and found it in includes/wc-template-functions.php.
In wc-template-functions.php the woocommerce_button_proceed_to_checkout() function just loads the template file which is just the button link code. I need to search further to find the hook that calls the woocommerce_button_proceed_to_checkout() function.
The woocommerce_button_proceed_to_checkout() function is called in includes/wc-template-hooks.php via the woocommerce_proceed_to_checkout action. Another search shows that this action is in run near the bottom of templates/cart/cart-totals.php.
Finding where to put the second button
Now that I know how the button code is generated I need to investigate where to add the code. Again, I will avoid modifying a template file.
I looked at the source of the Cart page and found the class of the cart form: ‘woocommerce-cart-form‘
I found this text in templates/cart/cart.php
Directly above the opening ‘form‘ tag is a ‘woocommerce_before_cart‘ action. This is an ideal location to for the second “Proceed to Checkout” link.
Wrap the link in a div
My first attempt was to simply call woocommerce_button_proceed_to_checkout() and let it pull in the template file.
When I opened the cart page the link was left aligned on the page. Using CSS to change the link would impact the link under the cart totals form. I decided to wrap it in a div.
CSS styling for desktop and mobile
On desktop I just floated the button to the right and added a bottom margin to separate it from the table below.
On mobile I display the link as a block (as it is just a simple ‘a’ element), remove the float and add some margins. It wouldn’t truly centre for me but I never figured out why.