The 16 Most Useful and Most Functional WooCommerce Snippets

In my article on the most useful WordPress snippets, I already announced that a report on the best WooCommerce snippets would follow soon. Et voilà, here are my best WooCommerce snippets.

You’ll know some of these snippets already, but I’m confident that I’ll be able to show you something new as well. Thus, I have summarized the best pieces in one post.

Compatibility:

  • WordPress from Version 4.6
  • WooCommerce from Version 3.xx
  • PHP-Version 7.xx

You either copy the snippets into your active theme’s functions.php, or you set up a page-specific plugin for the task.

Please do not copy the opening <?php.

[blue-box text=” Please keep in mind: Create a file backup before each change made to the functions.php. Don’t use the WordPress editor to alter the file. If something goes wrong, you’ll lose access to your website. Make your changes directly on your web hosting, via an FTP access.”]

1 – Providing WooCommerce Support for Your Theme

If your active theme is not prepared for using it with WooCommerce, you should start there and provide the support. That’s the only way to ensure that your new shop is displayed optimally. This process consists of three parts.

Part One: First, declare the support for your theme, and add a product lightbox if you want to.

<?php

/**
* Theme Support for WooCommerce
*/
add_theme_support( 'woocommerce' );  

/**
 * Add Theme Support for WooCommerce Gallery Lightbox
 */ 
add_theme_support( 'wc-product-gallery-lightbox' );


Part Two:
Remove WooCommerce’s opening and closing container DIVs from the plugin’s templates.

<?php

//remove function attached to woocommerce_before_main_content hook
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );

//remove function attached to woocommerce_after_main_content hook
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );


Part Three:
Replace the DIVs with the ones your theme uses. To do so, you have to figure out the names of your theme’s container DIVs. A right-click on your website, and “Inspect” can help you with that.

Find Your Content Containers. Here, they are highlighted.

Afterwards, add these containers to the following code:

<?php

if ( ! function_exists( 'evolution_wrapper_start' ) ) :
/**
 * Adding theme's starter container for WooCommerce support
 */
function evolution_wrapper_start() {
    
echo '<div id="primary" class="content-area"><main id="main" class="site-main" role="main">';
    
}
add_action( 'woocommerce_before_main_content', 'evolution_wrapper_start', 10 );
endif;



if ( ! function_exists( 'evolution_wrapper_end' ) ) :
/**
 * Adding theme's ending container for WooCommerce support
 */
function evolution_wrapper_end() {
    
    echo '</div></main>';
}
add_action( 'woocommerce_after_main_content', 'evolution_wrapper_end', 10 );
endif;

Now, your shop should be displayed just as well as the rest of your theme.

2 – Replacing WooCommerce Breadcrumbs With the Ones of Yoast SEO

A ton of WordPress fans uses the breadcrumb navigation of the popular Yoast SEO plugin. You can also use it on the WooCommerce pages. This snippet does the trick:

<?php

if ( ! function_exists( 'evolution_replace_breadcrumbs' ) ) :
/**
 * Replace WooCommerce Breadcrumbs with Yoast breadcrumbs
 */
function evolution_replace_breadcrumbs() {

    remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
    

    function evolution_yoast_breadcrumb() {

        if ( function_exists('yoast_breadcrumb') ) { 
            yoast_breadcrumb('<nav class="woocommerce-breadcrumb">','</nav>');
        }
    }
}
add_action( 'init', 'evolution_replace_breadcrumbs' );
endif;

3 – Change the Number of Products Displayed in a row

By default, WooCommerce shows four products in a row. Changing this is very simple.

<?php

/**
 * Change number of products per row to 3
 */ 
if (!function_exists('evolution_loop_columns') ) {

    function evolution_loop_columns() {
        return 3; // 3 Products in a row
    }
}
add_filter('loop_shop_columns', 'evolution_loop_columns');

4 – Change the Number of Related Products

You get to choose how many related products your theme shows. Sometimes, this can come in handy.

<?php

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Change number of related products on product page
 * Set your own value for 'posts_per_page'
 *
 */ 
if (!function_exists('evolution_related_products_args') ) {

    function evolution_related_products_args( $args ) {

        $args['posts_per_page'] = 4; // 4 related products
        $args['columns'] = 4; // All four in a row
        return $args;

    }
}
add_filter( 'woocommerce_output_related_products_args', 'evolution_related_products_args' );

5 – Define How Many Products are Displayed on a Page

If you have a lot, or very few products in your shop, it might make sense to edit the number of products per page.

<?php

/**
 * Custom Product Cols
 * @return 12 Products per Page
 */
if (!function_exists('evolution_loop_shop_per_page') ) {

    function evolution_loop_shop_per_page( $cols ) {

        $cols = 12;
        return $cols;

    }
}
add_filter( 'loop_shop_per_page', 'evolution_loop_shop_per_page', 20 );

6 – Hiding Other Shipping Rates When Shipping is Labelled as Free

Do you offer free product shipping? Then you should use this code, as WooCommerce typically shows all shipping options in the checkout area.

<?php

/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 */
if (!function_exists('evolution_hide_shipping_when_free_is_available') ) {

    function evolution_hide_shipping_when_free_is_available( $rates ) {
        $free = array();
        foreach ( $rates as $rate_id => $rate ) {
            if ( 'free_shipping' === $rate->method_id ) {
                $free[ $rate_id ] = $rate;
                break;
            }
        }
        return ! empty( $free ) ? $free : $rates;
    }
}
add_filter( 'woocommerce_package_rates', 'evolution_hide_shipping_when_free_is_available', 100 );

7 – Loading WooCommerce CSS and JavaScript Files on Shop Pages Only

WooCommerce loads its files on each page of your website, including the homepage, and the articles. Firstly, this does not make sense, and secondly, it slows down your site. Thus, you should use this snippet. With this one, WooCommerce files are only loaded where they are needed.

<?php

if (!function_exists( 'evolution_manage_woocommerce_styles' ) ) :
/**
* Optimize WooCommerce Scripts
* Removes WooCommerce styles and scripts from non WooCommerce pages.
*/  
function evolution_manage_woocommerce_styles() {

    //first check that woo exists to prevent fatal errors
    if ( function_exists( 'is_woocommerce' ) ) {

        //dequeue scripts and styles
        if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() && ! is_account_page() ) {          
            wp_dequeue_style( 'woocommerce-layout' );
            wp_dequeue_style( 'woocommerce-smallscreen' );
            wp_dequeue_style( 'woocommerce-general' );
            wp_dequeue_style( 'evolution-woostyles' );
            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' );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'evolution_manage_woocommerce_styles', 99 );
endif;

8 – Use a Unique Sidebar on the Shop Pages

About 95% of all developers don’t know how to solve this without overwriting WooCommerce templates. On the internet, you won’t really find a solution either, as most results will also suggest overwriting the templates.

So today, you’ll learn a secret from me :-) From now on, you’ll solve the problem like a Jedi, and not like a Padawan.

Part One: Create a New Sidebar for the WooCommerce Pages

<?php

if (!function_exists( 'evolution_woo_sidebar_init' ) ) :
/**
 * Registering a new sidebar exclusively for the shop pages 
 */
function evolution_woo_sidebar_init() {
    
    register_sidebar( array(
        'name'          => esc_html__( 'WooCommerce Sidebar', 'evolution' ),
        'id'            => 'woocommerce',
        'description'   => esc_html__( 'This is the sidebar for your WooCommerce Shop.', 'evolution' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
}
add_action( 'widgets_init', 'evolution_woo_sidebar_init' );
endif;

Part Two: Create a WooCommerce Sidebar File

For the new sidebar to be usable, we need a new theme file. Create an empty file called sidebar-woocommerce.php. To do so, please use an HTML editor.

Take the HTML containers from your sidebar.php. Now, add the following code to the file, and upload it to your theme, or child theme folder via (S)FTP.

<?php
/**
 * The sidebar containing the woocommerce widget area.
 *
 * @package Evolution Framework
 */
if (   ! is_active_sidebar( 'woocommerce' ) ) {
    return;
}
?>
<?php // Important: Copy the HTML containers from your sidebar.php ?>
<div id="secondary" class="sidebar-area" role="complementary">

    <div class="normal-sidebar widget-area">

        <?php if ( is_active_sidebar( 'woocommerce' ) ) : ?>

        <?php dynamic_sidebar( 'woocommerce' ); ?>

        <?php endif; ?>

    </div><!-- .normal-sidebar -->

</div><!-- #secondary -->

Part 3: Swap the Sidebars on the Shop Pages

The original function of the WooCommerce framework allows for the exchange of the two sidebars. All of these functions are “pluggable.” This means that they are easy to overwrite.

A rewritable function looks like this:

<?php

if (!function_exists( 'a_great_function' ) ) :
/**
 * Making a function rewritable 
 */
function a_great_function() {
    
    
}
add_action( 'great_function', 'a_great_function' );
endif;

The if (!function_exists( 'a_great_function' ) ) : means that the function is only executed if there is no other function with the said name. However, if there is a function with this name, the function is not executed. This is why these functions are so easy to rewrite. And we’ll do just that.

Exchanging the Sidebar: The Snippet

The following snippets result in the WooCommerce sidebar being displayed on your shop pages, instead of the regular sidebar.

<?php

/**
 * Get the spezial sidebar for the WooCommerce Templates
 * DO NOT CHANGE THIS FUNCTION, or the WooCommerce Sidebar will not work.
 * 
 * @overrides the woocommerce function
 * 
 * @hooked woocommerce_sidebar()
 */
function woocommerce_get_sidebar() {
    
    get_template_part( 'sidebar-woocommerce' );
    
}

Now, on all shop pages, instead of your sidebar.php, the file sidebar-woocommerce.php is accessed, and you get to fill both sidebars with different content.

9 – WooCommerce Checkout: Turn the Phone Number Into Voluntary Information

Entering your phone number at checkout is obligatory. I’m sure that several potential customers don’t like that. The following snippet makes it a voluntary option to enter the number.

<?php

if (!function_exists( 'evolution_phone_no_pflicht' ) ) :
/**
 * Make the phone number an optional entry
 * 
 * @hooked woocommerce_billing_fields()
 * 
 * @return filter
 */
function evolution_phone_no_pflicht( $address_fields ) {
    
    $address_fields['billing_phone']['required'] = false;

    return $address_fields;
}
add_filter( 'woocommerce_billing_fields', 'evolution_phone_no_pflicht', 10, 1 );
endif;

10 – Displaying Percentage Savings for Offers

Increase the psychologic purchase incentives by displaying your offers’ potential savings in percent.

<?php

if ( !function_exists( 'evolution_custom_sales_price' ) ) :
/**
 * Show percent savings on sale - Only for WooCommerce version 3.0+
 * 
 * @add filter to products
 * 
 * @return filter
 */
function evolution_custom_sales_price( $price, $regular_price, $sale_price ) {
    
    $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
    
    $percentage_txt = __(' Spare ', 'evolution' ).$percentage;
    
    $price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) . $percentage_txt : $sale_price . $percentage_txt ) . '</ins>';
    return $price;
    
}
add_filter( 'woocommerce_format_sale_price', 'evolution_custom_sales_price', 10, 3 );
endif;

11 – Add Your Share Buttons to the Product Page

To increase the range of your shop, users should be able to share each product on social media. Thus, it makes a lot of sense to display your share buttons on the product pages. To do so, the shortcode for the manual integration into a theme is required.

It can be found in the documentation of your WordPress theme. I’m using the Shariff Share-Buttons for my integration.

<?php

if (!function_exists( 'evolution_share_for_woocommerce' ) ) :
/**
 * Implementing share buttons on the page of an individual product
 * 
 * @hooked woocommerce_share()
 */
function evolution_share_for_woocommerce() {

    echo do_shortcode( '[[shariff]]' );
}
add_action( 'woocommerce_share', 'evolution_share_for_woocommerce', 5 );
endif;

The Result:

The Most Useful and Most Functional WooCommerce Snippets

12 – Removing Product Tabs From the Product View

The tabs can either be removed one by one or all at once, which can be advantageous at times.

<?php

if (!function_exists( 'evolution_remove_product_tabs' ) ) :
/**
 * Removing the product tabs of the description 
 * 
 * @hooked woocommerce_product_tabs()
 */
function evolution_remove_product_tabs( $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', 'evolution_remove_product_tabs', 98 );
endif;

13 – Live Cart Update Via Ajax

You don’t have to refresh the shopping cart to keep it up to date. Ajax “Live” is a much better way to do that.

<?php

if (!function_exists( 'evolution_header_add_to_cart_fragment' ) ) :
/**
 * Ensure cart contents update when products are added to the cart via AJAX
 * 
 * @add_filter woocommerce_add_to_cart_fragments
 */
function evolution_header_add_to_cart_fragment( $fragments ) {
    
    ob_start();
?>
<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->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a> 
<?php

    $fragments['a.cart-contents'] = ob_get_clean();

    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'evolution_header_add_to_cart_fragment' );
endif;

14 – Displaying a Link to the User Account in the Theme

If the user is not logged in, the link shows “Login/Register,” and uses the login page. If the user is logged in, the link reads “My Account,” and takes you straight to your user account.

 <?php if ( is_user_logged_in() ) { ?>
 	<a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('Mein Account','evolution'); ?>"><?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','evolution'); ?>"><?php _e('Login / Register','woothemes'); ?></a>
 <?php } ?>

15 – Adding the Customer Payment Method to the Admin Email

After each order, you receive an email from WooCommerce. With this snippet, you can add the customer’s payment method of choice to the email.

if (!function_exists( 'evolution_add_payment_method_to_admin_new_order' ) ) :
/**
 * Adding the customer's payment method to the admin email
 * 
 * @hooked woocommerce_email_after_order_table()
 */
function evolution_add_payment_method_to_admin_new_order( $order, $is_admin_email ) {
    
    if ( $is_admin_email ) {
        
        echo '<p><strong>Zahlungsart:</strong> ' . $order->payment_method_title . '</p>';
        
    }
}
add_action( 'woocommerce_email_after_order_table', 'evolution_add_payment_method_to_admin_new_order', 15, 2 );
endif;

16 – Change the Order of Fields in the Checkout Area

Using this snippet, you can adjust the WooCommerce checkout area. You get to edit the order of fields in the checkout area, or even remove them.

<?php

if (!function_exists( 'evolution_reorder_woo_fields' ) ) :
/**
 * Alter the order of fields in the checkout area, or remove them completely.
 * 
 * @add_filter woocommerce_checkout_fields
 */
function evolution_reorder_woo_fields( $fields ) {
    
    //move these around in the order you'd like
    $fields2['billing']['billing_first_name'] = $fields['billing']['billing_first_name'];
    $fields2['billing']['billing_last_name']  = $fields['billing']['billing_last_name'];
    $fields2['billing']['billing_company']    = $fields['billing']['billing_company'];
    $fields2['billing']['billing_address_1']  = $fields['billing']['billing_address_1'];
    $fields2['billing']['billing_address_2']  = $fields['billing']['billing_address_2'];
    $fields2['billing']['billing_city']       = $fields['billing']['billing_city'];
    $fields2['billing']['billing_postcode']   = $fields['billing']['billing_postcode'];
    $fields2['billing']['billing_state']      = $fields['billing']['billing_state'];
    $fields2['billing']['billing_country']    = $fields['billing']['billing_country'];
    $fields2['billing']['billing_email']      = $fields['billing']['billing_email'];
    $fields2['billing']['billing_phone']      = $fields['billing']['billing_phone'];

    //just copying these (keeps the standard order)
    $fields2['shipping'] = $fields['shipping'];
    $fields2['account']  = $fields['account'];
    $fields2['order']    = $fields['order'];

    return $fields2;
}
add_filter( 'woocommerce_checkout_fields', 'evolution_reorder_woo_fields' );
endif;

Andreas Hecht

Andreas Hecht is a journalist and specialist for WordPress and WordPress Security. He roams the web since its inception. He has published an ebook on WordPress Security, which you might want to take a look at.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz