How to Display WooCommerce Products By Category

WooCommerce Display Products by Category

Are you running a WooCommerce store and you want to display products by category in WordPress? This post has a detailed explanation of how to display WooCommerce products by category.

If you are familiar with WooCommerce, you know that product categories play an important role in organizing your products for proper display and access by your customers.

Display WooCommerce Products by Category

Right out of the box, WooCommerce gives you a few options as to what you can display on your archive pages such as products, categories, or subcategories or both products and categories.

However, most WooCommerce users opt for the third option to display both products and categories/subcategories.sort woocommerce categories

This option will allow your visitor to either select products right from the home page or refine their search by clicking through to a product category archive.

However, the main downside of this is that it displays the categories/subcategories together, with no separation between the two.

This makes the layout look a bit messy because of the different image dimensions.

From an expert point of view, even if your images are the same size, if one of the lines in the archive page includes both categories and products, the absence of an ‘Add to Cart’ button for categories makes that row look disorganized, as not all of its elements have the same dimensions.

In this brief tutorial, you will learn how to display categories in a separate list before displaying products.

  • Identify or distinguish the code in WooCommerce, which is used to output categories and subcategories on archive pages.
  • Create a custom plugin for the code.
  • Write a function that will put categories or subcategories before product listings.
  • Create a custom styling for the output.

a)    Display both Products and Categories or Subcategories

Steps to Display Both Products and Categories or Subcategories.

  1. Log into your WordPress site and access the Dashboard as the admin user.
  2. From the Dashboard menu, click on Appearance Menu > Customize. Click on the Shop page and select WooCommerce > Product Catalog. On the Shop Display option, select Show Categories & Products. On the Category display option, select Show subcategories & products as shown below:

 

Display WooCommerce Products by Category

Remember to save the changes that you make.

This will be the outcome:Display WooCommerce Products by Category

b)    Display WooCommerce Product Category

However, you can display the WooCommerce Product Category using a code snippet below, which should be placed in the functions.php file.

Steps to Display WooCommerce Product Category

Here are the steps that you should follow:

  1. Log into your WordPress site and access the Dashboard as the admin user.
  2. From the Dashboard menu, click on Appearance Menu > Theme Editor When the Theme Editor page is opened, look for the theme functions file where we will add the function that will display the WooCommerce Product category.
  3. Add the following code to the PHP file:
function woocommerce_product_category( $args = array() ) {

    $woocommerce_category_id = get_queried_object_id();

  $args = array(

             'parent' => $woocommerce_category_id
  );

  $terms = get_terms( 'product_cat', $args );

  if ( $terms ) {

             echo '<ul class="woocommerce-categories">';

             foreach ( $terms as $term ) {

             echo '<li class="woocommerce-product-category-page">';

            woocommerce_subcategory_thumbnail( $term );

             echo '<h2>';

             echo '<a href="' .  esc_url( get_term_link( $term ) ) . '" class="' . $term->slug . '">';

             echo $term->name;

             echo '</a>';

             echo '</h2>';

             echo '</li>';

             }

             echo '</ul>';

  }

}

add_action( 'woocommerce_before_shop_loop', 'woocommerce_product_category', 100 );
  1. This will be the Outcome:Display WooCommerce Products by Category

However, it needs some custom CSS for it to display the products well. We will do this later on in this tutorial.

How the Code Works

This code works by simply using the woocommerce_product_category() function which is outputting the categories or subcategories before running the loop which outputs the products. It can override the theme, as the function is pluggable.

c)    List Subcategories of a WooCommerce Product Category

It is very easy to get the subcategory of WooCommerce product categories by using a custom function that takes advantage of the parent product category slug.

Steps to List Subcategories of a WooCommerce Product Category

  1. Log into your WordPress site and access the Dashboard as the admin user.
  2. From the Dashboard menu, click on Appearance Menu > Theme Editor When the Theme Editor page is opened, look for the theme functions file where we will add the function that will List Subcategories of a WooCommerce Product Category.
  3. Add the following code to the PHP file:
function woocommerce_get_product_category_of_subcategories( $category_slug ){

$terms_html = array();
$taxonomy = 'product_cat';
$parent = get_term_by( 'slug', $category_slug, $taxonomy );
$children_ids = get_term_children( $parent->term_id, $taxonomy );

foreach($children_ids as $children_id){

    $term = get_term( $children_id, $taxonomy );

    $term_link = get_term_link( $term, $taxonomy );

    if ( is_wp_error( $term_link ) ) $term_link = '';

    $terms_html[] = '<a href="' . esc_url( $term_link ) . '" rel="tag" class="' . $term->slug . '">' . $term->name . '</a>';
}

return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';

}
  1. This will be the Outcome:List Subcategories of a WooCOmmerce Product category

How the code works.

The WP_Term object gets the product category parent. Then, it gets the child ID in an array, and finally, the child categories are displayed in the HTML by running a loop through the child ID array.

d)    Identifying the Code WooCommerce Uses to Output Categories and Products in Archives

Before we create a plugin, the first step is definitely to identify how WooCommerce outputs categories and subcategories. This means that we have to manually look for the WooCommerce source code to find the relevant function.

To simplify the process for you, simply look for the,archive-product.php, which is in the templates folder. This is the file that WooCommerce uses to display archive pages. You now need to find the code that outputs the categories and products:

<?php
/**
* woocommerce_before_shop_loop hook
*
* @hooked woocommerce_result_count - 20
* @hooked woocommerce_catalog_ordering - 30
*/

do_action( 'woocommerce_before_shop_loop' );
?>

<?php woocommerce_product_loop_start(); ?>

<?php woocommerce_product_subcategories(); ?>

<?php while ( have_posts() ) : the_post(); ?>

<?php wc_get_template_part( 'content', 'product' ); ?>

<?php endwhile; // end of the loop. ?>

<?php woocommerce_product_loop_end(); ?>

How the Code Works:

The woocommerce_product_subcategories() function outputs the categories or subcategories before running the loop which outputs the products.

The reason why I brought your attention to this function is that it is pluggable, which means we could override it in our theme.

However, this will not work as WooCommerce has built-in styling for clearing items, which would appear at the beginning of a row with the default display.

So what should we do? The answer is simple. We need to turn off the display of categories and subcategories on our archive pages so that just products are displayed.

After this, the next step is to create a new function that outputs the product categories or subcategories and hooks them to the woocommerce_before_shop_loop action, making sure we use a high priority so that it fires after the functions which are already hooked to that action.

It is however important to note that WooCommerce adds clears to each third product listing.

This means that we can’t use them woocommerce_product_subcategories() function or an edited version of it to display the categories.

The explanation for this is that this function will clear the third, sixth (and so on) category or product listed, even when we use this function to display categories separately.

This means that we have to create a function that would override it. This can be done by creating a plugin.

e)    Creating the Plugin

You need to first create a new folder and give it a unique name in the wp-content/plugins directory.

For this example, be careful when following the steps so that you can achieve the functionality that we need.

I am going to use this name njengah-separate-products-categories-in-archives.

Inside this folder, you need to create a new file, again with a unique name. I will use the same name as well for this folder njengah-separate-products-categories-in-archives.php.

Steps to Create the Plugin

  1. Open your file and add the following code:
<?php
/**
* Plugin Name: WooCommerce Product Category
* Description: Display WooCommerce categories on WooCommerce product pages

**/
  1. Before writing our function, you need to turn off category listings in the admin screens by Logging into your WordPress site and accessing the Dashboard as the admin user.
  2. From the Dashboard menu, click on Appearance Menu > Customize. Click on the Shop page and select WooCommerce > Product Catalog. On the Shop Display option, select Show Products. On the Category display option, select Show Products.
  3. Remember to save the changes that you make.
  4. This will be the outcome:Display WooCommerce Products by Category
  5. Add this to the plugin file:
function njengah_product_subcategories( $args = array()) {

}

add_action( 'woocommerce_before_shop_loop', 'njengah_product_subcategories', 50 );
  1. Then you need to add this code in the function:
  2. $parentid = get_queried_object_id();
    
    $args = array(
    
    'parent' => $parentid
    
    );
    
    $terms = get_terms( 'product_cat', $args );
    
    if ( $terms ) {
    
    echo '<ul class="product-cats">';
    
    foreach ( $terms as $term ) {
    
    echo '<li class="category">';
    
    woocommerce_subcategory_thumbnail( $term );
    
    echo '<h2>';
    
    echo '<a href="' .  esc_url( get_term_link( $term ) ) . '" class="' . $term->slug . '">';
    
    echo $term->name;
    
    echo '</a>';
    
    echo '</h2>';
    
    echo '</li>';
    
    }
    
    echo '</ul>';
    
    }

    This will be the result:Display WooCommerce Products by Category

As you can see from the above image, the categories are not organized well. This means that we have to add our custom styling.

However, before that, let us learn how the code works.

How the Code Works

The function that we created identifies the current queried object and defines its id as $parentid. Then it uses get_terms() to identify terms with the currently queried item as their parent.

If this is the main shop page, it will return top-level categories and if this is a category archive, it will return subcategories.

Moreover, the function checks if there are any terms, before opening for each loop and an ul element.

This means that for each term, it creates an li element, and then outputs the, category image using woocommerce_subcatgeory_thumbnail(),  followed by the category name in a link to its archive.

Steps to Style the Category Listings

These are the steps that you need to follow, but to do this we need a stylesheet inside our plugin, which we will need to enqueue.

  1. Create a folder called CSS, and inside that, create a file called CSS. This should be done in the plugin folder for this to work.
  2. Add this code at the top of the function you’ve already created:
function njengah_product_cats_css() {

/* register the stylesheet */

wp_register_style( ' njengah _product_cats_css', plugins_url( 'css/style.css', __FILE__ ) );

/* enqueue the stylsheet */

wp_enqueue_style( ' njengah _product_cats_css' );

}

add_action( 'wp_enqueue_scripts', ' njengah _product_cats_css' );
  1. The next step is to open your stylesheet and add the code below. However, it is important to note that WooCommerce uses mobile-first styling, so that is what we will be using too.
ul.product-cats li {
list-style: none;
margin-left: 0;
margin-bottom: 4.236em;
text-align: center;
position: relative;
}

ul.product-cats li img {
margin: 0 auto;
}


@media screen and (min-width:768px) {

ul.product-cats {
margin-left: 0;
clear: both;
}

ul.product-cats li {
width: 29.4117647059%;
float: left;
margin-right: 5.8823529412%;
}

ul.product-cats li:nth-of-type(3) {
margin-right: 0;
}

}
  1. This will be the outcome:Display WooCommerce Products by Category

Conclusion

In this post, I have highlighted different ways in which you can display WooCommerce products by category.

From this brief tutorial, you can understand why product categories are a great feature in WooCommerce, but the way they are displayed is not always ideal.

Additionally, you have learned how to create a plugin that outputs product categories or subcategories separately from the product listings, and how to style the category listings.

The most outstanding part of this tutorial is the creation of the custom plugin that outputs a list of categories or subcategories on the page, by hooking the function to a different action hook within the WooCommerce template file.

Similar Articles

Comments are closed.