0

I'm looking for a way to check if (whilst outside the loop) the current user.. 1. is logged in 2. has a post published 3. their post has any term/terms from a custom taxonomy

I have this so far...

<?php if (( 1 == count_user_posts( get_current_user_id(), "post" ) && is_user_logged_in() ) { ?>
blah blah
<?php } ?>

I'm just wildly guessing here but could I use if( has_term( '', 'custom-taxonomy' ) )? but that's for use inside the loop.

1

This can be done using WP_Query using author and tax_query.

Something like this:

$args = array(
    'post_type' => 'post',
    'author' => get_current_user_id(),
    'tax_query' => array(
        array(
            'taxonomy' => 'custom-taxonomy',
            'operator' => 'EXISTS'
        ),
    ),
);
$query = new WP_Query( $args );

And then check if posts are returned through this query.

Please note that this code is not tried or tested and may contain syntax errors.

4
  • How does this work outside the loop? and how does it fit within my conditional?
    – Pete
    Nov 23 '19 at 15:13
  • 1
    The query will return all the posts whose author is current user and those are tagged to any of the custom taxonomy. So if query is empty, no posts satisfying condition. Otherwise it satisfy your condition. And since it is a separate query, it does not need to be in the loop. Nov 25 '19 at 5:23
  • Yep, sorry I get it now.
    – Pete
    Nov 26 '19 at 10:04
  • This worked, thanks... <?php $args2 = array( 'post_type' => 'post', 'author' => get_current_user_id(), 'tax_query' => array( array( 'taxonomy' => 'day_time', 'operator' => 'EXISTS' ), ), ); $query2 = new WP_Query( $args2 ); ?> <?php // The Loop if ( $query2->have_posts() ) { while ( $query2->have_posts() ) { $query2->the_post(); ?> Well done <?php } } else { ?> You need to update your availability <?php } ?> <?php // Restore original Post Data wp_reset_postdata(); ?>
    – Pete
    Nov 26 '19 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.