20 Useful Woocommerce Snippets for WordPress Themes Woocommerce is increasingly becoming the eCommerce platform of choice for most new websites since it is not only easy to use but there are numerous freely available wooCommerce themes. In order to improve your Woocommerce development, there are several code snippets that make it easier for developers to build or customize wooCommerce themes. If you are new to WordPress theme customization the tutorial - How to get Started Customizing WordPress Themes is a good place to start.

From my experience, there are many snippets you can use to customize wooCommerce but the code snippets below have proven to be very useful and time-saving for my projects. I would like to share with you these snippets as the best WooCommerce snippets.

Best WooCommerce Snippets

The following code snippets should help you customize the WooCommerce functionality and form. These code snippets should help you to remove or add functionality to WooCommerce.

1) Declare WooCommerce support in a third party theme

The first most useful code is used for declaring WooCommerce support in your theme. This is a very important snippet that you can use to add WooCommerce support to any WordPress theme.
add_action( 'after_setup_theme', 'woocommerce_support' );

function woocommerce_support() {

add_theme_support( 'woocommerce' );

}

2) Adding Custom Currency to WooCommerce

WooCommerce by default To add a custom currency in WooCommerce 2.0+, copy and paste this code in your theme functions.php file and swap out the currency code and symbol with your own. After saving changes, it should be available from your WooCommerce settings.
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;}

3) To display the cart contents and total in your template

If you want to show the cart content and the total in your template you should use something like this:
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">

<?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> -

<?php echo WC()->cart->get_cart_total(); ?> </a>

4) Change the number of thumbnails per row in product galleries

I always want to change the thumbnail displayed per row in product galleries, I often use this code to change the display per row.

add_filter ( 'woocommerce_product_thumbnails_columns', 'xx_thumb_cols' );

function xx_thumb_cols() {

return 4; // .last class applied to every 4th thumbnail

}

5) Add a new country to the countries list

To add a new country to the countries list, use this snippet (you can paste it in the functions.php file within our theme folder):
/* Add a new country to countries list */

function woo_add_my_country( $country ) {

$country["AE-DU"] = 'Dubai';

return $country;

}

add_filter( 'woocommerce_countries', 'woo_add_my_country', 10, 1 );

6) Display My Account link in a template file

Displays a link to the user account section. If the user is not logged in the link will display ‘Login / Register’ and take the use to the login / signup page. If the user is logged in the link will display ‘My account’ and take them directly to their account.
<?php if ( is_user_logged_in() ) { ?>

<a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account','woothemes'); ?>"><?php _e('My Account','woothemes'); ?></a>

<?php }

else { ?>

<a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('Login / Register','woothemes'); ?>"><?php _e('Login / Register','woothemes'); ?></a>

<?php } ?>

7) Display a checkout link in a template file

This snippet displays a link to your checkout when there are products in the cart. If you want to display the checkout link regardless, remove the if statement
global $woocommerce;

if ( sizeof( $woocommerce->cart->cart_contents) > 0 ) :

echo '<a href="' . $woocommerce->cart->get_checkout_url() . '" title="' . __( 'Checkout' ) . '">' . __( 'Checkout' ) . '</a>';

endif;

8) Change the number of products displayed per page

If you want to display 25 product per page you should add this code to your functions.php. You can also alter that number to your preference.
// Display 25 products per page. Goes in functions.php

add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 25;' ), 20 );

9) Set Image Dimension

Add the following snippet to your themes functions.php file to adjust the quantity inputs behavior.

Set the starting value, maximum value, minimum value and increment amount
<?php
/**
* Hook in on activation
*/
/**
* Define image sizes
*/
function yourtheme_woocommerce_image_dimensions() {

global $pagenow;

if ( ! isset( $_GET['activated'] ) || $pagenow != 'themes.php' ) {

return;
}
$catalog = array(
'width' => '400', // px
'height' => '400', // px
'crop' => 1 // true
);
$single = array(
'width' => '600', // px
'height' => '600', // px
'crop' => 1 // true
);
$thumbnail = array(
'width' => '120', // px
'height' => '120', // px
'crop' => 0 // false
);
// Image sizes
update_option( 'shop_catalog_image_size', $catalog ); // Product category thumbs
update_option( 'shop_single_image_size', $single ); // Single product image
update_option( 'shop_thumbnail_image_size', $thumbnail ); // Image gallery thumbs
}

10) Automatically Complete Orders

Sometimes I like it when the cart automatically completes the orders. To achieve this auto-completion I use the following block of code
/**
* Auto Complete all WooCommerce orders.

* Add to theme functions.php file

*/
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );

function custom_woocommerce_auto_complete_order( $order_id ) {

global $woocommerce;

if ( !$order_id )

return;

$order = new WC_Order( $order_id );

$order->update_status( 'completed' );

}

11) Change email subject lines

Default Woocommerce email subject line are not the best, you can customize theme using the following code:
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;

}

12 ) Adjust the quantity input values

Add the following snippet to your themes functions.php file to adjust the quantity inputs behavior. Set the starting value, maximum value, minimum value and increment amount.
// Simple products

add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 );

function jk_woocommerce_quantity_input_args( $args, $product ) {

$args['input_value'] = 2; // Starting value

$args['max_value'] = 80; // Maximum value

$args['min_value'] = 2; // Minimum value

$args['step'] = 2; // Quantity steps

return $args;

}

// Variations

add_filter( 'woocommerce_available_variation', 'jk_woocommerce_available_variation' );

function jk_woocommerce_available_variation( $args ) {

$args['max_qty'] = 80; // Maximum value (variations)

$args['min_qty'] = 2; // Minimum value (variations)

return $args;

}

13) Allow shortcodes in product excerpts

Shorcodes in WordPress make it very easy for you to publish content without editing theme core files. To allow shortcodes in product excerpts, I use the following code.
Add the following to your themes functions.php file.

if (!function_exists('woocommerce_template_single_excerpt')) {

function woocommerce_template_single_excerpt( $post ) {

global $post;

if ($post->post_excerpt) echo '<div itemprop="description">' . do_shortcode(wpautop(wptexturize($post->post_excerpt))) . '</div>';

}

14) Change add to cart button text

Customizing the cart button allows you to display text in your preferred text. You can add the following to your functions.php file to change add to the cart button text.
//Single Page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' ); // 2.1 +
function woo_custom_cart_button_text() {
return __( 'My Button Text', 'woocommerce' );

}
//On Archive Pages
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_archive_custom_cart_button_text' ); // 2.1 +
function woo_archive_custom_cart_button_text() {
return __( 'My Button Text', 'woocommerce' );
}

15) Products loop

This is the most important snippet I use regularly to display the products. The product loop is very useful when you are creating a page template to showcase products. Here is the products loop.
<ul class="products">
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;

} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->

16) Remove the breadcrumbs

Occasionally, you want to remove the breadcrumbs, here is a quick snippet to help you remove woocommerce breadcrumbs from your pages.
add_action( 'init', 'jk_remove_wc_breadcrumbs' );
function jk_remove_wc_breadcrumbs() {
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );

}

17) Replace shop page title

Using this block of code you can quickly, replace the title of your shop. Just substitute the return value with your preferred name.
add_filter( 'woocommerce_page_title', 'woo_shop_page_title');

function woo_shop_page_title( $page_title ) {

if( 'Shop' == $page_title) {

return "My new title";

}

}

18) Order by price, date, or title on the shop page

Ordering product by price, date, and title is a good way to help customers sort out the products on your site. The following snippet helps you to order the products by price, date, or title.
add_filter('woocommerce_default_catalog_orderby', 'custom_default_catalog_orderby');

function custom_default_catalog_orderby() {

return 'date'; // Can also use title and price

}

19) Redirect to the checkout page after adding to cart

To improve the sales conversions , automatically redirecting to checkout page after adding product to cart is a cool move. To auto redirect customers to checkout when they add products to cart, use the following code:
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', 16 );

20) Remove product categories from shop page

If you want to get rid of a certain product category from your shop page, this code is very useful. Maybe you don't want to display a certain category of product on shop since they are not the best sellers, use this snippet.
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

if ( ! $q->is_main_query() ) return;

if ( ! $q->is_post_type_archive() ) return;

if ( ! is_admin() && is_shop() && ! is_user_logged_in() ) {

$q->set( 'tax_query', array(array(

'taxonomy' => 'product_cat',

'field' => 'slug',

'terms' => array( 'color', 'flavor', 'spices', 'vanilla' ), // Don't display products in these categories on the shop page

'operator' => 'NOT IN'

)));}

remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

Conclusion

I have shared the most useful snippets I use in my day-to-day Woocommerce development, I hope this list helps you to quickly edit wooCommerce themes and woocommerce websites.

If you are new to wooCommerce development, these snippets should help you get started with wooCommerce development as well as make a good reference for you in the future. I would like to get feedback from you. If you have additional comments, compliments, or want to share your wooCommerce snippets with us, please feel free to leave us a comment.