Woocommerce Snippets – Complete Collection 2020

When developing an ecommerce website with WooCommerce, you must have encountered a lot of obstacles in changing WooCommerce to suit what you want. Realizing this, I decided to make a comprehensive list of all the code snippets that can help you solve the problem quickly.

Changing these features will work based on leveraging Hooks and Filters in WooCommerce, but if the theme you’re using doesn’t use hooks and filters, it probably won’t work.

The code snippets for WooCommerce have been tested and run well, so you just need to copy it and paste it into the functions.php file of the theme you are using.

To facilitate the arrangement, these code snippets will be organized according to the customer’s shopping process.

Starting from displaying products in the shop page, to the product display page, then the cart page, followed by the payment page, and finally the account page.

This article also includes some paragraphs that may help you when displaying products with shortcodes.

Let’s begin, folks!

WooCommerce Shop Page Code Snippets

The shop page is the page that displays all of your existing products. And maybe for a variety of reasons, you want to show more different information, like notifications for each type of customer, display more product reviews …

Let’s start with the first snippet!

Custom Message for different User Roles

In some situations, you must give alerts to each type of customer when they visit your shop page, this is the snippet you need.

function hqhowdotcom_custom_messages() {

    //you can change reseller to your desire user role to show message
	if (is_user_logged_in()) {
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;
        if (in_array("reseller", $roles)) {
            echo 'Welcome back, ' .$user->display_name 'We hope you are safe during this Covid-19 epidemic', 'hqhowdotcom' ), esc_html(  ) );
    //you can change woocommerce_archive_description to other hook, like woocommerce_before_shop_loop, woocommerce_after_shop_loop
add_action( 'woocommerce_archive_description', 'hqhowdotcom_custom_messages', 9 );

Show Star Rating in Product Item Loop

Some template you use may hide product review statistics while on the shop page, so if you want to briefly show reviews for each product, use this snippet

add_action('woocommerce_after_shop_loop_item', 'hqhowdotcom_add_star_rating' );
function hqhowdotcom_add_star_rating() {
    if (is_shop()) {

        global $woocommerce, $product;
        $average = $product->get_average_rating();
        echo '<div class="product-start-rating"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).'</span></div>';

Show Variation Options on WooCommerce Shop List

By default, WooCommerce does not display product options for customers to choose directly on the shop page. For some reason you want to display options such as color, size … for each product, right at the shop page, this code snippet will help you.

function hqhowdotcom_add_variant_select_on_shop_loop() {
	remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
	add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_single_add_to_cart', 30 );

After displaying it, maybe you don’t like the display anymore, you can hide the “Add to cart” button and the “Select Options” in the shop page completely, the code snippet will be simpler. , it will look like this:

add_filter( 'woocommerce_loop_add_to_cart_link', function( $product ) {

	global $product;

	if ( is_shop() && $product->is_type( 'variable' )) {
		return '';
	} else {
		sprintf( '<a href="%s" data-quantity="%s" class="%s" %s>%s</a>',
			esc_url( $product->add_to_cart_url() ),
			esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
			esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
			isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
			esc_html( $product->add_to_cart_text() )
} );

Show Quantity on Product List

This is cool, guys, now how to display more boxes to enter the number of products you want to buy, right on the shop page?

If you have to ask, copy the code below.

add_filter( 'woocommerce_loop_add_to_cart_link', 'hqhowdotcom_quantity_input', 10, 2 );
function hqhowdotcom_quantity_input( $html, $product ) {
	if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
		$html = wc_get_template_html( 'single-product/add-to-cart/simple.php' );
	return $html;

Change Default PlaceHolder Image

Some products that you forgot to add featured photos, it will look a little bad with the default image.

You can use this code snippet to change the image you want.

add_filter('woocommerce_placeholder_img_src', 'hqhowdotcom_change_default_placeholder_image');

function hqhowdotcom_change_default_placeholder_image( $src ) {
    //you can change the size, background color and the text on it also.
    //if you want to use your image, just alternate the link
	$src = 'https://via.placeholder.com/728x90.png/000000?text=This%20placeholder%20image%20is%20created%20by%20https://hqhow.com';
	return $src;

WooCommerce Product Page Code Snippets

So the changes on the shop page are done, now we will move on to the changes on the product details page.

Well, a lot of changes can be made on this page, so sit tight, guys!

Remove Product Meta on Single Product Page

On several occasions when working with my customer, my customer imports from the manufacturer and directly uses the factory SKU code on the website.

This may reveal a bit of business information so they asked me to hide it, so ye, do it.

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );

Only 1 line, easy!

Remove Product tab on Single Product Page

Last time when I made a website for a customer, they sold ebooks about business process training, and the “Additional Information” tab didn’t really meet their needs, so I had to remove it.

add_filter( 'woocommerce_product_tabs', 'hqhowdotcom_remove_product_tabs', 98 );

function hqhowdotcom_remove_product_tabs( $tabs ) {
    unset( $tabs['additional_information'] );  	// Remove the additional information tab

    return $tabs;

In fact, this function can remove both the description and review tabs, so if you want to remove one more line, change the additional_information to “description” or “review” if desired.

Remove Zero Decimals in Product Price

 add_filter( 'woocommerce_price_trim_zeros', '__return_true' );

Custom Product Option

When applying this, read it carefully, guys. First of all, make a simple hypothesis.

Suppose you want to add an input field to the product posting page at wp-admin, and at the frontend, on the product details page, you can display it, under the add to cart button.

Instead of having to explain it to you little by little, I explain it right in the code for you to understand.

//add custom field to woocommerce product post page
add_action( 'woocommerce_product_options_advanced', 'hqhowdotcom_add_option_to_advanced_tab');
function hqhowdotcom_add_option_to_advanced_tab(){
	echo '<div class="options_group">';
	woocommerce_wp_checkbox( array(
		'id'      => 'product_benefit',
		'value'   => get_post_meta( get_the_ID(), 'product_benefit', true ),
		'label'   => 'Product Benefit',
		'desc_tip' => true,
		'description' => 'Describe what is your product benefit',
	) );
	echo '</div>';
//save the field's value on saving product 
add_action( 'woocommerce_process_product_meta', 'hqhowdotcom_update_option_value', 10, 2 );
function hqhowdotcom_update_option_value( $id, $post ){

		update_post_meta( $id, 'product_benefit', $_POST['product_benefit'] );

//show the field under add to cart button
add_action( 'woocommerce_after_add_to_cart_button', 'hqhowdotcom_custom_product_option_single_product_page', 60);
function hqhowdotcom_custom_product_option_single_product_page()
	global $product;
    // get the product id first
	$product_id = $product->get_id();
	// get the product meta data
	$product_benefit = get_post_meta($product_id, 'product_benefit', true);
	// Show the Form if product is Custom
	if (isset($product_benefit)){
		echo '<h5> What is benefit when buying from us?</h5>';
		echo $product_benefit;

Cool, isn’t it? So what a pity but don’t give me a share, guys?

Woocommerce Cart Code Snippets

Okay, the product detail page is good enough, now it’s time to go to the cart page! Deploy now!

Show Discounted Price on Total Column

Oke, this will show the original price and the price has been reduced in “Total” on the shopping cart page, only it will create transparency in displaying prices and more peace of mind when shopping on the website of friend.

add_filter( 'woocommerce_cart_item_subtotal', 'hqhowdotcom_show_discounted_price_in_cart_table', 99, 3 );
add_filter( 'woocommerce_cart_item_price', 'hqhowdotcom_show_discounted_price_in_cart_table', 99, 3 );

function hqhowdotcom_show_discounted_price_in_cart_table( $subtotal, $cart_item, $cart_item_key ) {

	global $woocommerce;

	// Check if cart has coupon.
	if ( ! $woocommerce->cart->has_discount() ) {
		return $subtotal;

	// Get coupons.
	$coupons = WC()->cart->get_applied_coupons();

	// Loop through coupons.
	foreach ( $coupons as $coupon ) {

		// Create coupon object.
		$coupon = new WC_Coupon( $coupon );

		// Check if specific coupon is applied.
		if ( $woocommerce->cart->has_discount( $coupon->get_code() ) ) {

			// Check if products in cart are from a specific category).
			if ( has_term( $coupon->product_categories, 'product_cat', $cart_item['product_id'] ) ) {

				// If coupon type is fixed_product.
				if ( 'fixed_product' === $coupon->get_discount_type() ) {
					$newsubtotal = wc_price( $cart_item['data']->get_price() - $coupon->get_amount() * $cart_item['quantity'] );
				} else { // If coupon type is percentage.
					$newsubtotal = wc_price( $cart_item['data']->get_price() * ( 1 - ( '0.' . $coupon->get_amount() ) ) * $cart_item['quantity'] );

				$subtotal = sprintf( '<s>%s</s> %s', $subtotal, $newsubtotal );

	return $subtotal;

Hide Quantity on Cart Page

It sounds strange, but if you are selling event tickets, the information is filled in the product detail page, then going through the shopping cart page to change the number of tickets will not be very logical, so it’s best for us to hide this quantity column.

function hqhowdotcom_remove_quantity_column( $return, $product ) {
	if ( is_cart() ) return true;
add_filter( 'woocommerce_is_sold_individually', 'hqhowdotcom_remove_quantity_column', 10, 2 );

WooCommerce Checkout Code Snippets

Optimizing the payment page at WooCommerce is a laborious task. There are quite a few plugins out there that can help you achieve your goal simply, but if you want to be even simpler, don’t need the plugin, you can use the woocommerce snippets below that I provide to help you get rid of the plugins.

Remove Billing Fields

Normally, for each type of website, there will be corresponding input boxes on the payment page.

For example, a website selling ebooks will not need shipping boxes, as well as boxes about company information … so this snippet will help you remove unnecessary fields.

add_filter( 'woocommerce_checkout_fields' , 'hqhowdotcom_remove_checkout_fields' );
function hqhowdotcom_remove_checkout_fields( $fields ) {

//available options to remove: billing_first_name, billing_last_name, billing_company, billing_address_1, billing_address_2, billing_city, billing_postcode, billing_country, billing_state, billing_email, billing_phone

return $fields;

Add Custom Billing Fields

In addition to eliminating unnecessary fields, adding fields to the checkout page is also extremely necessary, to achieve perfection in customizing the checkout page.

You should use this snippet to add the fields you want.

add_filter( 'woocommerce_checkout_fields' , 'hqhowdotcom_add_custom_checkout_fields' );

// Add the company code on the billing form
function custom_override_checkout_fields( $fields ) {
     $fields['billing']['billing_company_code'] = array(
        'label'     => __('Company Code', 'woocommerce'),
    'placeholder'   => _x('Company code: 3801083518', 'placeholder', 'woocommerce'),
    'required'  => false,
    'class'     => array('form-row-wide'),
    'clear'     => true

     return $fields;

 * Display field value on the order edit page
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'hqhowdotcom_add_company_code_to_order_detail', 10, 1 );

function hqhowdotcom_add_company_code_to_order_detail($order){
    echo '<p>'.__('Company Code').':' . get_post_meta( $order->get_id(), '_shipping_phone', true ) . '</p>';

Add Custom Checkout Fields

You can also add fields outside of the billing and shipping forms by following them.

But with these fields outside of billing and shipping, you have to do a few other things. The code snippet below will help you do that.

 * Add delivery date picker on Checkout page, after order note
add_action( 'woocommerce_after_order_notes', 'hqhowdotcom_delivery_date_picker_checkout_field' );

function delivery_date_picker_checkout_field( $checkout ) {

    echo '<div id="delivery_date_checkout_field"><h2>' . __('Delivery Date') . '</h2>';

    woocommerce_form_field( 'order_delivery_date', array(
        'type'          => 'text',
        'class'         => array('delivery-date-class form-row-wide'),
        'label'         => __('Delivery Date'),
        'placeholder'   => __('04/26/2020'),
        ), $checkout->get_value( 'order_delivery_date' ));

    echo '</div>';


 * Update the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'hqhowdotcom_save_delivery_date_to_order_detail' );

function hqhowdotcom_save_delivery_date_to_order_detail( $order_id ) {
    if ( ! empty( $_POST['order_delivery_date'] ) ) {
        update_post_meta( $order_id, 'order_delivery_date', sanitize_text_field( $_POST['order_delivery_date'] ) );

 * Show custom field value in order detail
add_action( 'woocommerce_admin_order_data_after_billing_address', 'hqhowdotcom_show_delivery_date_in_order_detail', 10, 1 );

function hqhowdotcom_show_delivery_date_in_order_detail($order){
    echo '<p><strong>'.__('Delivery Date').':</strong> ' . get_post_meta( $order->id, 'order_delivery_date', true ) . '</p>';

Limit WooCommerce Order Note Length

With WooCommerce, at the checkout page, customers can add order notes to the order.

For some reason, you want to limit the number of characters that customers can write to the order note, then use the following snippet.

add_filter( 'woocommerce_checkout_fields', 'hqhow_limit_order_note_length' );

function hqhow_limit_order_note_length( $fields ) {
	$fields['order']['order_comments']['maxlength'] = 200;
	return $fields;

Show Custom Billing Checkout Fields by Product ID

Sometimes you will need to display some custom fields for certain products, to do this on WooCommerce, you can refer to this WooCommerce code snippets.

add_action( 'woocommerce_checkout_fields', 'hqhowdotcom_cutom_checkout_field_conditional_logic' );

function hqhowdotcom_cutom_checkout_field_conditional_logic( $fields ) {

	foreach( WC()->cart->get_cart() as $cart_item ){
	    $product_id = $cart_item['product_id'];

            //change 2020 to your product id
			if( $product_id == 2020 ) {
				$fields['billing']['billing_field_' . $product_id] = array(
					'label'     => __('Custom Field on Checkout for ' . $product_id, 'woocommerce'),
					'placeholder'   => _x('Custom Field on Checkout for ' . $product_id, 'placeholder', 'woocommerce'),
					'required'  => false,
					'class'     => array('form-row-wide'),
					'clear'     => true


	// Return checkout fields.
	return $fields;


Hide All Shipping Method But Free Shipping

In the user experience, you should automatically apply the free shipping method whenever possible, which helps customers feel more comfortable with your purchase.

The code snippet below will help you do this.

function hqhowdotcom_only_show_free_shipping_when_available( $rates, $package ) {
	$new_rates = array();
	foreach ( $rates as $rate_id => $rate ) {
		// Only modify rates if free_shipping is present.
		if ( 'free_shipping' === $rate->method_id ) {
			$new_rates[ $rate_id ] = $rate;

	if ( ! empty( $new_rates ) ) {
		//Save local pickup if it's present.
		foreach ( $rates as $rate_id => $rate ) {
			if ('local_pickup' === $rate->method_id ) {
				$new_rates[ $rate_id ] = $rate;
		return $new_rates;

	return $rates;

add_filter( 'woocommerce_package_rates', 'hqhowdotcom_only_show_free_shipping_when_available', 10, 2 );

Remove Completely Shipping Form

If you are selling ebooks or digital products, having shipping fields is no longer necessary.

Therefore, we should always turn off the WooCommerce shipping form at the checkout page.

  1. Go to WooCommerce Settings
  2. At the General Settings tab, find Shipping location(s) option
  3. Select Disable shipping & shipping calculations

Woocommerce 2 Column Checkout

This is more related to CSS than PHP, the code snippet for this is the one I apply when: not using the shipping form, shortening some fields in the billing form.

Here’s the result:

@media (min-width: 993px) {
.woocommerce-checkout .col2-set .col-1{width:100%;}
.woocommerce-checkout .woocommerce-billing-fields h3{margin-top:40px;}
.woocommerce-checkout .col2-set, .woocommerce-checkout .col2-set{width:42%;float:left;}
#order_review_heading, .woocommerce-checkout #order_review, .woocommerce-checkout #order_review{float:left;width:42%;margin-left:6%;}
.woocommerce-checkout h3#order_review_heading {   margin: 18px 70px !important;}

WooCommerce My Account Code Snippets

This is the last page that we should optimize during the process from viewing the product to buying from customers.

Actually, the My Account page is quite complete, but if you want to know the ways people are applying to their My Account page, you can see the following code snippets.

WooCommerce 2 Column My Account

This code snippet is applicable when you allow others to register on your page because with this, there is enough information to split into 2 columns.

Another CSS code snippet!

@media (min-width: 993px) {
.woocommerce-account .u-column1.col-1,
		.woocommerce-account .u-column2.col-2 {
			width: 50%;
			padding: 50px;
			text-align: left;


Remove Columns on Download Table

Once the customer has purchased his ebook, we can hide the columns like domain remaining download if you have unlimited downloads. This will give you some extra space to display the product title and the download table will look better.

add_action( 'woocommerce_account_downloads_columns', 'hqhowdotcom_remove_download_remaining_column', 10, 1 ); // Orders and account
add_action( 'woocommerce_email_downloads_columns', 'hqhowdotcom_remove_download_remaining_column', 10, 1 ); // Email notifications
function hqhowdotcom_remove_download_remaining_column( $columns ){

    // Removing "Download remaining" column

    return $columns;

General Optimizations

In WooCommerce, you can display products related to existing products so that customers can buy them together, but these products may not display correctly.

To increase the accuracy of displaying related products, we can limit the product scope to search within the current category.

add_filter('woocommerce_related_products', 'hqhowdotcom_increase_related_product_accuracy_woocommerce');
function filter_woocommerce_related_products_args($args)
    global $post;

    // get the cats this product is in
    $terms = get_the_terms($post->ID, 'product_cat');

    // if there is only one category jump out.
    if (count($terms) === 1) {
        return $args;

    // get all product cats for the current post
    $categories = get_the_terms( get_the_ID(), 'product_cat' ); 
    $cats = [];

    // wrapper to hide any errors from top level categories or products without category
    if ( $categories && ! is_wp_error( $category ) ) {
        foreach($categories as $category) {
            $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
            if ( count($children) == 0 ) {
                $cats[] = $category->term_id;

    $post_ids = get_posts(array(
        'post_type' => 'product',
        'numberposts' => -1, // get all posts.
        'tax_query' => array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $cats,
            // Remove current product
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $post->ID,
                'operator' => 'NOT IN',
        'fields' => 'ids', // Only get post IDs

    // Alter the query
    $args['post__in'] = $post_ids;

    return $args;

DeQueue WooCommerce Styles and Scripts

WooCommerce uses quite a lot of files, sometimes on unnecessary places, it also loads these resources.

To speed up your website, you may not be able to load these resources of WooCommerce in the way below.

If you’re embedding WooCommerce products on other pages, don’t use it.

add_action( 'wp_enqueue_scripts', 'hqhowdotcom_dequeue_woocommerce_styles_scripts', 99 );

function hqhowdotcom_dequeue_woocommerce_styles_scripts() {
    if ( function_exists( 'is_woocommerce' ) ) {
        if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
            # Styles
            wp_dequeue_style( 'woocommerce-general' );
            wp_dequeue_style( 'woocommerce-layout' );
            wp_dequeue_style( 'woocommerce-smallscreen' );
            wp_dequeue_style( 'woocommerce_frontend_styles' );
            wp_dequeue_style( 'woocommerce_fancybox_styles' );
            wp_dequeue_style( 'woocommerce_chosen_styles' );
            wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
            # Scripts
            wp_dequeue_script( 'wc_price_slider' );
            wp_dequeue_script( 'wc-single-product' );
            wp_dequeue_script( 'wc-add-to-cart' );
            wp_dequeue_script( 'wc-cart-fragments' );
            wp_dequeue_script( 'wc-checkout' );
            wp_dequeue_script( 'wc-add-to-cart-variation' );
            wp_dequeue_script( 'wc-single-product' );
            wp_dequeue_script( 'wc-cart' );
            wp_dequeue_script( 'wc-chosen' );
            wp_dequeue_script( 'woocommerce' );
            wp_dequeue_script( 'prettyPhoto' );
            wp_dequeue_script( 'prettyPhoto-init' );
            wp_dequeue_script( 'jquery-blockui' );
            wp_dequeue_script( 'jquery-placeholder' );
            wp_dequeue_script( 'fancybox' );
            wp_dequeue_script( 'jqueryui' );

Remove or Disable Password Strength

add_filter( 'woocommerce_min_password_strength', 'hqhowdotcom_password_strength', 10 );
function hqhowdotcom_password_strength() {
return 2; } //2 represent medium strength password. 0 to disable

In Conclusion

So the list of code snippets for WooCommerce has been completed.

If you find any code snippets not working, please leave a comment, we will update immediately

If you find this article helpful, please help us share this article to everyone!

  1. This is great stuff. Just wondering, would you also happen to know how to make the Your Order section switch places with the Billing section? By default, Billing comes before (ie. is placed above) Your Order but I am wondering if Your Order can come first. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like