0
votes

My code was working properly, but accidentally I deleted something, but I don't remember what. At this moment my plugin display only one, last user. Before everything was ok and plugin could display all users. Do you have any ideas? Thanks in advance

function my_count_posts_by_user(){

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

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

   $result = $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);
}

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

    echo'<td>'.'ID: '. $x['ID']."</td>";
    echo'<td>'.'User : '. $x['display_name'].'</td>';
    echo'<td>'.'Number of posts :'. $x['Number_of_posts'].'</td>';
    echo'</tr>';

}

echo '</table>';
echo '<br>';
2

2 Answers

0
votes

I think you should use WP API functions which will do everything for you.

  • get_users() function will get all users data just define fields which u require.
  • get_user_meta() function will get user meta data.

A small example

 $users = get_users( array( 'fields' => array( 'ID' ) ) );
 foreach( $users as $user_id ) {
     print_r( get_user_meta( $user_id->ID ) );
 }
0
votes

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++){

       $result = $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);


        echo '<table>';
        foreach ($result as $x){
            echo'<tr>'; 
            echo'<td>'.'ID: '. $x['ID']."</td>";
            echo'<td>'.'User : '. $x['display_name'].'</td>';
            echo'<td>'.'Number of posts :'. $x['Number_of_posts'].'</td>';
            echo'</tr>';
        }
        echo '</table>';
        echo '<br>';
    }
}