-1

I working on my simple wordpress plugin. This plugin should rank all users based off number of written posts and then display it on html table. Everything works fine, except sorting. Do you have any ideas how to sort this array by Number_of_posts value?

for($id = 1;$id<=$total_users;$id++){

    $ar = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, 
                                    COUNT(wp_posts.post_author) AS 'Number_of_posts' 
                            FROM wp_users 
                                INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author 
                            WHERE  wp_posts.post_type = 'post'  
                            AND wp_users.ID = $id 
                            AND wp_posts.post_status = 'publish'" ,         
                            ARRAY_A);


    function sort($a, $b) {
        return $a['Number_of_posts'] - $b['Number_of_posts'];
    }

    usort($ar, 'sort');

    foreach ($ar as $x){
        echo'<tr>'; 

        echo'<td>'. $x['ID']."</td>";
        echo'<td>'. $x['display_name'].'</td>';
        echo'<td>'. $x['Number_of_posts'].'</td>';
        echo'</tr>';
    }
}

echo '</table>';
echo '<br>';
Vel
  • 9,027
  • 6
  • 34
  • 66
skirnich57
  • 29
  • 3

1 Answers1

0

Try this code

function my_count_posts_by_user(){

    global $wpdb; 
    $result = count_users();
    $total_users = $result['total_users'];

    for($id = 1;$id<=$total_users;$id++){

        $ar = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, 
                                COUNT(wp_posts.post_author) AS 'Number_of_posts' 
                        FROM wp_users 
                            INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author 
                        WHERE  wp_posts.post_type = 'post'  
                        AND wp_users.ID = $id 
                        AND wp_posts.post_status = 'publish' order by  Number_of_posts desc" ,         
                        ARRAY_A);

        //usort($ar, 'sort');
        echo '<table>';
        foreach ($ar as $x){
            echo'<tr>'; 

            echo'<td>'. $x['ID']."</td>";
            echo'<td>'. $x['display_name'].'</td>';
            echo'<td>'. $x['Number_of_posts'].'</td>';
            echo'</tr>';
        }
    }

    echo '</table>';
    echo '<br>';
}
Vel
  • 9,027
  • 6
  • 34
  • 66