Right now I’m using this complex Query.
First I query users and then query their posts by specific custom taxonomy:
<?php
$args = array(
'meta_query' => array(
//Buy traffic if UserFunds is greater than 0
array(
'key' => 'userfunds',
'value' => '0',
'compare' => '>',
),
),
'number' => 999999999,
'orderby' => 'rand',
);
$my_user_query = new WP_User_Query( $args );
$advertisers = $my_user_query->get_results();
if ( ! empty( $advertisers )): ?>
<?php foreach ( $advertisers as $advertiser ):
setup_postdata( $advertiser ) ?>
<!-- If Advertisers with Funds exist, filter out campaign posts -->
<?php
$advertiser_info = get_userdata( $advertiser->ID );
// Get posts with custom taxonomy 'type' => 'campaign'
$posts = get_posts(array(
'author' => $advertiser_info->ID,
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'slug',
'terms' => array( 'campaign' ),
),
),
'post_type' => 'post',
'posts_per_page' => 1,
'orderby' => 'rand',
));
if( $posts): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post )
?>
<?php echo the_title(); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<?php echo 'no posts';?>
<?php endif; ?>
<!-- // END of If Advertisers with Funds exist do the following -->
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<?php echo 'no users';?>
<?php endif; ?>
The problem with the above code is that it’s a post loop inside a user loop.
Which means, it will output 1 random post for each user.
So if there’s 500 users with that custom taxonomy, it would output 1 random post per 1 user. (because it’s in the user loop).
What I want is basically to output 1 post out of all the WordPress users who match those two criterias (user_meta and post taxonomy).
Ideally merge user_meta and post custom taxonomy into one query.
I can’t set 'number' => 1,
for user query, because if only 1 user gets through, but he/she doesn’t have the post with that custom taxonomy, nothing will be shown.
I need to show at least one post, which is why I’m fetching 9999999 users and then filtering posts from them.
Need help. It’s too complex for me as a newbie.