Deep
Deep

Reputation: 23

How to sort categories by number of posts in wordpress?

I'm using this syntax for ordering categories by the number of posts in each categories.

<?php wp_list_categories('title_li=&show_count=1&child_of=3&number=5&orderby=count'); ?>

Still it's not working.. It shows the categories ordered alphabetically. Please help me!

Please see the sidebar

http://www.primobazaar.com/

Upvotes: 2

Views: 5324

Answers (2)

The Humble Rat
The Humble Rat

Reputation: 4696

Here is some code I have modified from another answer

<?php
    echo '<ul>';
    foreach (get_categories('orderby=count&order=ASC') as $category ) 
    {
         if( $category->category_parent == '0') 
         { 
            $url = '';
            $url =  site_url() . '/' . $category->taxonomy . '/' . $category->slug ;
            echo '<li class="cat-item cat-item-' . $category->term_id . '"><a href="' . $url . '">' . $category->name . ' (' . $category->count . ')</a></li>';

         }
    }
    echo '</ul>';
?>

Here is the question that led to the answer.

http://wordpress.org/support/topic/cant-get-wp_list_categories-to-list-by-count-help

Removing the $category->category_parent == '0' if check, will mean that all categories will be selected and not just parents.

Hope this helps.

Update

Change the line ('orderby=count&order=ASC') to ('orderby=count&order=DESC') for descending ordering. Also you will have to add your further arguments etc, ie &child_of=3&number=5.

Upvotes: 4

Moeed Farooqui
Moeed Farooqui

Reputation: 3622

get_posts

    <?php
$args = array(
    'posts_per_page'   => 5,
    'offset'           => 0,
    'category'         => '',
    'orderby'          => 'post_date',   <----------------
    'order'            => 'DESC',        <----------------
    'include'          => '',
    'exclude'          => '',
    'meta_key'         => '',
    'meta_value'       => '',
    'post_type'        => 'post',
    'post_mime_type'   => '',
    'post_parent'      => '',
    'post_status'      => 'publish',
    'suppress_filters' => true );

$posts_array = get_posts( $args );
 ?> 

You can sort them how you want like menu_order,post_date etc.

Upvotes: 0

Related Questions