phpwordpressadvanced-custom-fieldsacfpro

List User by use role with count of posts they are assigned to


I want to show a list of users by role with a count of how many posts they are assigned to. I use an ACF user field to assign posts to users, here is what I have so far, not sure if I am headed in the right direction.

$args_user_role = array(
    'role'    => 'um_pds-project-manager',
    'orderby' => 'user_nicename',
    'order'   => 'ASC'
);
$users = get_users( $args_user_role );

$args_projects = array(
  'posts_per_page' => -1,
  'post_type' => 'project',
  'meta_query' => array(
            'relation' => 'AND',
    array(
        'key'   => 'status',
        'value' => '1'
    ),
          array(
        'key' => 'pds_project_manager',
        'value' => $users,
        'compare' => 'LIKE'
    )
  )
);
$posts = get_posts($args_projects);
$pm_count = count($posts);//this is the total number of posts

Solution

  • This might work for you. I have a repeater field set up like this:

    enter image description here

    And the return value of the sub field is set to a user array:

    enter image description here

    Then loop through the post and repeater and add usernames, post ids, count and anything else you like to an array ($user_arr):

    foreach($posts as $post):
        if ( have_rows('user_repeater') ) :
            while( have_rows('user_repeater') ) : the_row();
                $user_arr = get_sub_field('user');
                $arr[$user_arr['user_nicename']]['post_ids'][] =  $post->ID;
                $arr[$user_arr['user_nicename']]['post_count']++;
            endwhile;
        endif;
    endforeach;
    

    My array looks like this, you can use this to create your list:

    enter image description here