My 25 Best WooCommerce Snippets For WordPress Part 2
Last updated on:

- 1. My 25 Best WooCommerce Snippets For WordPress
- 2. Currently Reading: My 25 Best WooCommerce Snippets For WordPress Part 2
A few days ago I wrote a post where I listed 25 of the most useful WooCommerce snippets I use and you were many people to ask for more, so today i decided to provide some more snippets for WooCommerce! Here we go!
1 – Replace WooCommerce default PayPal logo
/*
* Replace WooCommerce default PayPal icon
*/
function paypal_checkout_icon() {
return 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_betalen_met_paypal_nl.jpg'; // write your own image URL here
}
add_filter( 'woocommerce_paypal_icon', 'paypal_checkout_icon' );
2 – Replace default product placeholder image
/*
* goes in theme functions.php or a custom plugin. Replace the image filename/path with your own :)
*
**/
add_action( 'init', 'custom_fix_thumbnail' );
function custom_fix_thumbnail() {
add_filter('woocommerce_placeholder_img_src', 'custom_woocommerce_placeholder_img_src');
function custom_woocommerce_placeholder_img_src( $src ) {
$upload_dir = wp_upload_dir();
$uploads = untrailingslashit( $upload_dir['baseurl'] );
$src = $uploads . '/2012/07/thumb1.jpg';
return $src;
}
}
3 – Remove “Products” from breadcrumb
/*
* Hide "Products" in WooCommerce breadcrumb
*/
function woo_custom_filter_breadcrumbs_trail ( $trail ) {
foreach ( $trail as $k => $v ) {
if ( strtolower( strip_tags( $v ) ) == 'products' ) {
unset( $trail[$k] );
break;
}
}
return $trail;
}
add_filter( 'woo_breadcrumbs_trail', 'woo_custom_filter_breadcrumbs_trail', 10 );
4 – Empty cart
/*
* Empty WooCommerce cart
*/
function my_empty_cart(){
global $woocommerce;
$woocommerce->cart->empty_cart();
}
add_action('init', 'my_empty_cart');
5 – Automatically add product to cart on visit
/*
* Add item to cart on visit
*/
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 64;
$found = false;
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
add_action( 'init', 'add_product_to_cart' );
6 – Add a custom currency / symbol
add_filter( 'woocommerce_currencies', 'add_my_currency' );
function add_my_currency( $currencies ) {
$currencies['ABC'] = __( 'Currency name', 'woocommerce' );
return $currencies;
}
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);
function add_my_currency_symbol( $currency_symbol, $currency ) {
switch( $currency ) {
case 'ABC': $currency_symbol = '$'; break;
}
return $currency_symbol;
}
7 – Change add to cart button text
/**
* Change the add to cart text on single product pages
*/
function woo_custom_cart_button_text() {
return __('My Button Text', 'woocommerce');
}
add_filter('single_add_to_cart_text', 'woo_custom_cart_button_text');
/**
* Change the add to cart text on product archives
*/
function woo_archive_custom_cart_button_text() {
return __( 'My Button Text', 'woocommerce' );
}
add_filter( 'add_to_cart_text', 'woo_archive_custom_cart_button_text' );
8 – Redirect subscription add to cart to checkout page
/**
* Redirect subscription add to cart to checkout page
*
* @param string $url
*/
function custom_add_to_cart_redirect( $url ) {
$product_id = (int) $_REQUEST['add-to-cart'];
if ( class_exists( 'WC_Subscriptions_Product' ) ) {
if ( WC_Subscriptions_Product::is_subscription( $product_id ) ) {
return get_permalink(get_option( 'woocommerce_checkout_page_id' ) );
} else return $url;
} else return $url;
}
add_filter('add_to_cart_redirect', 'custom_add_to_cart_redirect');
This snippet requires the Subscriptions plugin.
9 – Redirect to checkout page after add to cart
/**
* Redirect subscription add to cart to checkout page
*
* @param none
*/
function add_to_cart_checkout_redirect() {
wp_safe_redirect( get_permalink( get_option( 'woocommerce_checkout_page_id' ) ) );
die();
}
add_action( 'woocommerce_add_to_cart', 'add_to_cart_checkout_redirect', 11 );
10 – CC all emails
/**
* WooCommerce Extra Feature
* --------------------------
*
* Add another email recipient to all WooCommerce emails
*
*/
function woo_cc_all_emails() {
return 'Bcc: youremail@yourdomain.com' . "\r\n";
}
add_filter('woocommerce_email_headers', 'woo_cc_all_emails' );
11 – Send an email when a new order is completed with coupons used
/**
* WooCommerce Extra Feature
* --------------------------
*
* Send an email each time an order with coupon(s) is completed
* The email contains coupon(s) used during checkout process
*
*/
function woo_email_order_coupons( $order_id ) {
$order = new WC_Order( $order_id );
if( $order->get_used_coupons() ) {
$to = 'youremail@yourcompany.com';
$subject = 'New Order Completed';
$headers = 'From: My Name ' . "\r\n";
$message = 'A new order has been completed.\n';
$message .= 'Order ID: '.$order_id.'\n';
$message .= 'Coupons used:\n';
foreach( $order->get_used_coupons() as $coupon) {
$message .= $coupon.'\n';
}
@wp_mail( $to, $subject, $message, $headers );
}
}
add_action( 'woocommerce_thankyou', 'woo_email_order_coupons' );
12 – Change related products number
/**
* WooCommerce Extra Feature
* --------------------------
*
* Change number of related products on product page
* Set your own value for 'posts_per_page'
*
*/
function woo_related_products_limit() {
global $product;
$args = array(
'post_type' => 'product',
'no_found_rows' => 1,
'posts_per_page' => 6,
'ignore_sticky_posts' => 1,
'orderby' => $orderby,
'post__in' => $related,
'post__not_in' => array($product->id)
);
return $args;
}
add_filter( 'woocommerce_related_products_args', 'woo_related_products_limit' );
13 – Exclude products from a particular category on the shop page
/**
* Remove products from shop page by category
*
*/
function woo_custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'shoes' ), // Don't display products in the shoes category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
add_action( 'pre_get_posts', 'woo_custom_pre_get_posts_query' );
14 – Change shop columns number
/**
* WooCommerce Extra Feature
* --------------------------
*
* Change product columns number on shop pages
*
*/
function woo_product_columns_frontend() {
global $woocommerce;
// Default Value also used for categories and sub_categories
$columns = 4;
// Product List
if ( is_product_category() ) :
$columns = 4;
endif;
//Related Products
if ( is_product() ) :
$columns = 2;
endif;
//Cross Sells
if ( is_checkout() ) :
$columns = 4;
endif;
return $columns;
}
add_filter('loop_shop_columns', 'woo_product_columns_frontend');
15 – Disable WooCommerce tabs
/**
* Remove product tabs
*
*/
function woo_remove_product_tab($tabs) {
unset( $tabs['description'] ); // Remove the description tab
unset( $tabs['reviews'] ); // Remove the reviews tab
unset( $tabs['additional_information'] ); // Remove the additional information tab
return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tab', 98);
16 – Remove breadcrumb
/**
* Remove WooCommerce BreadCrumb
*
*/
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20);
17 – Restrict shipping countries list
/**
* WooCommerce Extra Feature
* --------------------------
*
* Restrict shipping countries list
*
*/
function woo_override_checkout_fields( $fields ) {
$fields['shipping']['shipping_country'] = array(
'type' => 'select',
'label' => __('My New Country List', 'woocommerce'),
'options' => array('AU' => 'Australia')
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );
18 – Replace “Free!” product string
/**
* WooCommerce Extra Feature
* --------------------------
*
* Replace "Free!" by a custom string
*
*/
function woo_my_custom_free_message() {
return "This product is FREE!";
}
add_filter('woocommerce_free_price_html', 'woo_my_custom_free_message');
19 – Hide ALL other shipping methods when Free Shipping is available
// Hide ALL shipping options when free shipping is available
add_filter( 'woocommerce_available_shipping_methods', 'hide_all_shipping_when_free_is_available' , 10, 1 );
/**
* Hide ALL Shipping option when free shipping is available
*
* @param array $available_methods
*/
function hide_all_shipping_when_free_is_available( $available_methods ) {
if( isset( $available_methods['free_shipping'] ) ) :
// Get Free Shipping array into a new array
$freeshipping = array();
$freeshipping = $available_methods['free_shipping'];
// Empty the $available_methods array
unset( $available_methods );
// Add Free Shipping back into $avaialble_methods
$available_methods = array();
$available_methods[] = $freeshipping;
endif;
return $available_methods;
}
20 – Make checkout “state” field not required
/**
* WooCommerce Extra Feature
* --------------------------
*
* Make "state" field not required on checkout
*
*/
add_filter( 'woocommerce_billing_fields', 'woo_filter_state_billing', 10, 1 );
add_filter( 'woocommerce_shipping_fields', 'woo_filter_state_shipping', 10, 1 );
function woo_filter_state_billing( $address_fields ) {
$address_fields['billing_state']['required'] = false;
return $address_fields;
}
function woo_filter_state_shipping( $address_fields ) {
$address_fields['shipping_state']['required'] = false;
return $address_fields;
}
21 – Create a coupon programatically
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
22 – Change email subject lines
/*
* Subject filters:
* woocommerce_email_subject_new_order
* woocommerce_email_subject_customer_procesing_order
* woocommerce_email_subject_customer_completed_order
* woocommerce_email_subject_customer_invoice
* woocommerce_email_subject_customer_note
* woocommerce_email_subject_low_stock
* woocommerce_email_subject_no_stock
* woocommerce_email_subject_backorder
* woocommerce_email_subject_customer_new_account
* woocommerce_email_subject_customer_invoice_paid
**/
add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2);
function change_admin_email_subject( $subject, $order ) {
global $woocommerce;
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$subject = sprintf( '[%s] New Customer Order (# %s) from Name %s %s', $blogname, $order->id, $order->billing_first_name, $order->billing_last_name );
return $subject;
}
23 – Add custom fee to cart
/**
* WooCommerce Extra Feature
* --------------------------
*
* Add custom fee to cart automatically
*
*/
function woo_add_cart_fee() {
global $woocommerce;
if ( is_cart() ) {
$woocommerce->cart->add_fee( __('Custom', 'woocommerce'), 5 );
}
}
add_action( 'woocommerce_before_cart_table', 'woo_add_cart_fee' );
24 – Custom added to cart message
/**
* Custom Add To Cart Messages
* Add this to your theme functions.php file
**/
add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
global $woocommerce;
// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
$return_to = get_permalink(woocommerce_get_page_id('shop'));
$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
else :
$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
endif;
return $message;
}
25 – Add payment method to admin email
/**
* WooCommerce Extra Feature
* --------------------------
*
* Add payment method to admin new order email
*
*/
add_action( 'woocommerce_email_after_order_table', 'woo_add_payment_method_to_admin_new_order', 15, 2 );
function woo_add_payment_method_to_admin_new_order( $order, $is_admin_email ) {
if ( $is_admin_email ) {
echo '<p><strong>Payment Method:</strong> ' . $order->payment_method_title . '</p>';
}
}
And boom! That’s it! I hope you’ll like these snippets. If you have any suggestions, don’t hesitate to leave a comment below!
Don’t have a WooCommerce ready theme, or want a new one? Make sure to checkout our Total WordPress theme!
I really very like a list 25 Best WooCommerce Snippets For WordPress. I follow and read a lot of posts on your site and get many tips for me. Thanks for sharing this article. Look forward to hearing more information from you!
thanks for posting these. looks like some very useful tips!
I really appreciate the snippets you have provided.
Rather than creating a page for each category that contains the category shortcode, such as [product_categories number=”17″ columns=”3″], I would like to pass the category number via a menu link.
That way one page can service any category.
Is this possible through the menu or a filter?
Thanks.
add_filter( ‘woocommerce_default_address_fields’,
function ( $fields ) {
$fields[‘state’][‘required’] = false;
return $fields;
}
);
thanks for this great content i want to ask that #offtopic how to remove my wootheme logo which says powered by wootheme.
thank you
Use a CSS snippet with display: none;
Thanks Remi, Great work. Could you please write a snippet to change “READ MORE” text in product listings. Add to Cart text replaced by Read More for all sold out items and I would like it to display as SOLD. Please help
These are useful codes Remi, Thanks a lot. Is there an extensive list of woocommerce order replacement codes we can use in the email templates to pull in customer and order information? From the templates I’ve been able to figure out that %o pulls in the order id and %s pulls in the blog name. Is there one for first name and last name etc, this would really be good to personalise the emails sent to clients a bit more.
Great stuff Remi!
Consider Part I && Part II bookmarked =)
Hi Remi,
Thank you for this wonderful ressource! I have a couple questions regarding changing the add to cart button texts.
For one thing, I’ve been testing WooCommerce 2.1 beta 2 on a dev site in preparation for a project I’ll start next week. I tried the code you supplied but it’s having no effect whatsoever. I have other filters working so I was wondering if you know if either the filter names for modifying add to cart button text changed in 2.1 or if there’s a bug that should be fixed before final.
I also found some code in the WC docs that uses different filters that do work:
http://docs.woothemes.com/document/change-add-to-cart-button-text/
woocommerce_product_single_add_to_cart_text
woocommerce_product_add_to_cart_text
Secondly and related to the working filters just above, there’s usually at least 2 types of add to cart buttons, “Add to Cart” for simple products and “Select Options” for variable products. If I want to target one or the other, do you know the conditional that can be used in the filter function?
Thanks again! I recently discovered your site as an awesome WooCOmmerce ressource. You do great work here! 🙂
Hi Remi,
Great snippets.
I was looking certain snippets related to coupon use. But I see that there are only a few (if not none) that change the behaviour or placement of the coupon entry box.
Is it difficult, or woocommerce doesn’t have hooks for coupon box, or is it just no one is interested to change the coupon box?
Do you have a snippets to make the coupon code as required? I don’t use (bypass) the cart so this will only applied to the checkout page.
Other thing is how to keep payment method displayed and applied when user use a coupon with 100% discount?
I learned that woocommerce logic is that when the discount is 100% means a payment method is not important anymore. But I think, especially for manual payment, it is still relevant because we want to know which method is prefered by user.
I also use a snippet to change the order status to complete only on one payment method. Since it is bypassed when using 100% discount, the status is not changed.
I really hope you have the solution for this.
Thank you
Rio
Hello and thanks very much for these. I was wondering do you have a way to rename the “Products” breadcrumb to something else? It says HOME | PRODUCTS | ITEM1, and I would like it to say HOME | SHOP| ITEM1. Thanks so much and have a nice day
Have a look at customizing the WooCommerce breadcrumbs.
thank you for your reply. I have Breadcrumb NavXT, so these don’t work. Do you have a way for Breadcrumb NavXT? Thank you very much
Nope, I don’t use the plugin sorry. I use a custom breadcrumbs plugin I developed for myself 😉
Apart from these useful code snippets, the WooCommerce Poor Guys Swiss Knife Plugin, offers a set of tools to customize and enhance a WooCommerce instance. It allows to to manage and customize checkout forms, minimum and maximum settings for products and cart and a lot more.
Cool looking plugin, thank you for sharing Baltasar!
Excellent tips.. Thank you very much.
What’s a good way to change ‘Add to Cart’ to ‘Go to Product’ if the product has already been purchased?
Hi,
Is there a snippet to EMPTY CART AUTOMATICALLY everytime someone leaves checkout page. This is because I want guests to only be able to buy one product at a time and see the summary of one product only.
Thanks for your help.
Hey, you seem like you know your WooCommerce!
I have been struggling with this lately, maybe you could help point me in the right direction?
I am trying to change the add to cart button to remove from cart if it has already been added to cart.
Any ideas? Thanks for the sweet blog!
Have a look at this other great post by Remi explaining how to check if a product is in the cart.
Great stuff!
Would it be too cheeky to ask for one more?
How does one add a ‘sold out’ badge on a product when it is purchased and runs out of stock instead of ‘out of stock’ which should only be for items that are actually out of stock and have not sold.
Cheers
A
I think it would look something like this:
Hi, thanks for your tips.
One question, I would like to know where I have to put this code to override the woocommerce code?
In my functions.php theme?
Yes in functions.php is fine 😉
Great post!! I have bookmarked 1 & 2!
Is there a way to set it up so that when they click ‘buy now’ on the shop page…that they go directly to PayPal. Id like to bypass the product page and the checkout pages….
Thank you!
Hi Brenda, yes you can do what you want by following the instructions on their website for setting up Paypal Express.
It would be really useful in the admin email to list the purchased products according to their category, like:
Sports Equipment
helmet…[price info]
ball……..[price info]
Athletic Wear
headband…..[price info]
running shirt [price info]
and although I didn’t do it above, for each product list to be alphabetized in each category.
Currently I don’t think the default email echos category at all. In fact what I get is (I think) a list of products in the order that the purchaser added them to the cart.
Thank you for the great snippets!
Thanks a lot for the snippets. The problem is, after updating the plugin, all that needs to be done again with accepting unwanted sideffects. 🙁
you don’t need to do it again as the snippets must be placed in functions.php. If you use a parent theme and a child theme you can update the plugin and the parent theme without having to re-add the snippets.
Hello, can someone help how to put all the categories on my homepage without using short codes. Thanks
The easiest would be using the get_terms function.
Great little bits of code, I’m looking for something similar that I can put in the {theme}/functions.php that will:
Add the ORDER TIME to:
1. Customer order confirmation email
2. New order admin email
3. Invoice and delivery not printouts using the ‘WooCommerce Print Invoices & Delivery Notes’ plugin.
Does anyone have some way of doing this?
Hi there,
Can anyone help on snippets/code to change the default titles of the woocommerce Billing Address / Shipping Address as it appears site wide? We need to edit them but cannot find anything on how to do so anywhere!! Tried a couple of things with using child theme but this does not change them site wide.
Any ideas? Would be greatly appreciated! Thanks!
This is well documented on the WooCommerce site – http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
Hi everyone.Can anyone help on snippets/code to rename last name,firstname,phone label and free shipping in check out page.Thank you so much!
Have a look at the previous comment, how to change the checkout fields are fully documented on the WooThemes site (link above).
Thank you for all you snippets. Many will be very helpful. I have one question. Do you think it would be possible to change “Restrict shipping countries list” snippet to “Restrict shipping STATES list”? Kind regards