I used the the following script (only with get_permalink….) to display posts from a post type where the post author has an extra meta field on his user page:
<?php // get users from user page
$blogusers = get_users();
foreach ($blogusers as $user) {
if(get_field('races','user_' . $user->ID)) {
while(the_repeater_field('races','user_' . $user->ID)) {
$signed_up = get_sub_field('race_name', $post_object->ID);
if($original_id == $signed_up->ID) { //original ID is the race_name post we are on
$user_info = get_userdata($user->ID);
$arg = array(
'post_type' => array ('members'),
'post_status' => array( 'publish'),
'posts_per_page' => 200,
'author' => $user_info->ID
);
$arg_query = new WP_Query();
$arg_query->query( $arg );
echo $total = $arg_query->post_count;
} else {
}
}
}
} ?>
While it worked to display titles of the posts from the members post type, I can’t get my head around to count these posts. It shows: 1 1 1 instead of 3 and so on.
How can I change the foreach to work properly?
2 Answers
Edit: Re-reading your question I noticed I may have mixed some things up, but the point remains that you should combine these separate queries performed inside the loop, by using variables inside the loop to create a comprehensive list of the query arguments that you can use to perform one query outside the loop.
I’ve unfortunately got no time to provide a more detailed answer.
Original post:
You’re getting 1 1 1
because you’re performing a separate query for each user.
You can combine these queries into one query and then $arg_query->post_count
will work as you want it to. To do this, use the foreach loop to get all author ids, storing them in an array. Then after the foreach loop is finished you perform the query, using the stored author ids for the author arg.
The WP_Query codex page shows this basic example for querying posts from multiple authors:
$query = new WP_Query( 'author=2,6,17,38' );
btw, why use get_userdata()
if you’re only using it to get the user ID
, which you already have?