user1002272
user1002272

Reputation:

Sort Category/taxonomy based on post count in wordpress

Is there a way to sort category/taxonomy list based on number of posts it contains?

regards, Desizner

Upvotes: 4

Views: 6144

Answers (4)

Rafael Xavier
Rafael Xavier

Reputation: 1063

You can use get_categories() function and pass one of these values in 'taxonomy': 'category' (to get only categories) or 'post_tag' (to get only tags) or even remove this key and it'll get both. Bellow we're ordering by posts counting on each category DESC.

<?php

$categories = get_categories([
    'taxonomy' => 'category',
    'orderby'  => 'count',
    'order'    => 'DESC'
]);

foreach ($categories as $category) {
   // Do something
}

?>

Upvotes: 3

jeojavi
jeojavi

Reputation: 886

Currently (September 2017) I also do it using wp_list_categories (as Ryan B) but with the following code:

<?php wp_list_categories( array(
    'orderby'    => 'count',
    'order'      => 'DESC'
) ); ?>

Upvotes: 2

adrenalin
adrenalin

Reputation: 135

<?php    
    foreach (get_categories('orderby=count&order=DESC') as $category ) 
    {
    /*Some stuff here*/
    }

?>

For more details take a look at: https://developer.wordpress.org/reference/functions/get_categories/

Upvotes: 1

Ryan B
Ryan B

Reputation: 3392

Yes there is, see wp_list_category

<?php wp_list_category('orderby=count'); ?>

is what you would use

Upvotes: 0

Related Questions