GWcode Categories Examples

Here are some examples to demonstrate what you can do with GWcode Categories:

Example 10 - Sorting categories

In this example, I'm going to show you how to grab a list of categories and then sort them to show a
"Newest categories" list and a "Most popular categories" list.

To get the list I want, I'm going to use the code below. It gets the categories with depth 3 or 4 in category group 5 and shows the number of entries for those categories:

{exp:gwcode_categories group_id="5" depth="3|4" entry_count="yes"}
	{cat_name} ({entry_count})
{/exp:gwcode_categories}

The output looks like this:

  • E-Commerce (1)
    • Magento (2)
  • Content Management System (1)
    • ExpressionEngine (4)
    • Wordpress (0)

Newest categories, sorting them by cat_id

To re-order the list above so that the categories which have been added the latest are at the top, you can use the orderby and sort parameters. For the orderby parameter, I'm going to use "cat_id", since the categories you've added latest will have the highest category ID. For the sort parameter, I'm going to use "desc" as the categories with the highest category ID's should be at the top. For clarification, I've also added the {cat_id} variable in the output so you can see how the list is being sorted.

{exp:gwcode_categories group_id="5" depth="3|4" entry_count="yes" orderby="cat_id" sort="desc"}
	{cat_name} ({entry_count}) ← ID: {cat_id}
{/exp:gwcode_categories}

The output will then be:

  • Wordpress (0) ← ID: 67
  • ExpressionEngine (4) ← ID: 65
  • E-commerce (1) ← ID: 64
  • Content Management System (1) ← ID: 22
  • Magento (2) ← ID: 20

Most popular categories, sorting them by entry_count and cat_name

If you want to show a most popular categories list, which has the categories with the most entries at the top, you'll have to use "entry_count" for the orderby parameter and "desc" for the sort parameter. If you also want to make sure that categories with the same number of entries are sorted alphabatically (A at the top, Z at the bottom), you can add "cat_name" as a second value for the orderby parameter and "asc" as a second value for the sort parameter like so:

{exp:gwcode_categories group_id="5" depth="3|4" entry_count="yes" orderby="entry_count|cat_name" sort="desc|asc"}
	{cat_name} ({entry_count}) ← ID: {cat_id}
{/exp:gwcode_categories}

..making the output look like this:

  • ExpressionEngine (4) ← ID: 65
  • Magento (2) ← ID: 20
  • Content Management System (1) ← ID: 22
  • E-commerce (1) ← ID: 64
  • Wordpress (0) ← ID: 67

As you can see, Content Management System and E-commerce have the same number of entries (1) and Content Management System is listed first because of the second parameter values for the orderby and sort parameters (cat_name, asc).