Changing the number of columns on the Shop page

You can do a lot with the free plugins available at WordPress.org, without any developer skills or with a limited budget, and this is probably the right course of action. If, however, you have time to dig into the code, then you can sometimes get modest speed increases by writing a few lines of code instead of loading a big plugin. With this recipe, I'm going to show you how to change the number of columns on your shop page without a plugin. We're going to code it manually.

Getting ready

You'll need to have a few products on your site so that you can see how the columns rearrange.

How to do it…

In order to change the number of columns on the Shop page, go through the following steps:

  1. Open up your theme's functions.php file, located under wp-content/themes/your-theme-name/. Optionally, you could create your own custom WooCommerce plugin as instructed in the Creating a WooCommerce plugin recipe in Chapter 1, WooCommerce Basics.
  2. In it, we're only going to add four lines of code:
    add_filter( 'loop_shop_columns', 'woocommerce_cookbook_loop_shop_columns', 20 );
    function woocommerce_cookbook_loop_shop_columns( $cols ) { 
        return 3; 
    }

    If you save and upload this file, you'll notice that there are three columns, but they don't look very good because we haven't changed our CSS. To make this look nice, we have to alter our CSS to match.

    How to do it…
  3. Open up your theme's style.css stylesheet so we can add some extra styles.
  4. Paste in the following code at the bottom of your stylesheet:
    .woocommerce ul.products li.product, .woocommerce-page ul.products li.product{ 
        width: 30.75% 
    }
  5. Save the file and upload it.

Your columns should now fill the available space.

Note

Most themes add extra margins and padding on your products. For that reason, you need to leave an extra buffer in your calculations. That's why, for three products, I chose to use 30.75 percent instead of 33.3 percent. You can tweak the width value until you get it just right.

There's more...

Some custom themes use pluggable functions. If the number of columns isn't changing, there are some alternative ways to write this code so that it works with pluggable functions. You can find a few examples at http://docs.woothemes.com/document/change-number-of-products-per-row/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset