简体   繁体   中英

Show 'no posts' message in Wordpress if user is logged in but they have no posts yet

I am currently using the code below. It displays links to all posts published by the current logged in user. I want to show the "No posts" message if the current logged in user has no posts yet. Grateful for all assistance.

<?php if ( is_user_logged_in() ): global $current_user; 
wp_get_current_user();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
while($author_posts->have_posts()) : $author_posts->the_post();
?>
<p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<?php endwhile; ?>
<?php else : ?>
<p>No posts</p>
<?php endif; ?>

You need to add another if condition inside the if ( is_user_logged_in() ) to check if there are any posts for the current user.

If you break down the logic of what you want to do first, this helps you to plan how to code it, eg

  • if user is logged in:
    • if they have posts display the posts
    • else display "no posts"
  • else: display "no posts"

Now applying that logic in your code:

<?php 
// IF USER IS LOGGED IN
if ( is_user_logged_in() ): 
    global $current_user; 
    wp_get_current_user();
    $author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
    $author_posts = new WP_Query($author_query);

    // IF THEY HAVE POSTS, DISPLAY THE POSTS
    if ($author_posts->have_posts()):
        while($author_posts->have_posts()) : $author_posts->the_post();
        ?>
            <p><a href="<?php the_permalink(); ?>">
               <?php the_title(); ?>
               <span class="date"><?php the_time('F j, Y'); ?></span>
            </a></p>
        <?php endwhile; ?>

    <?php 
    // ELSE (IF THEY HAVE NO POSTS) DISPLAY MESSAGE
    else : ?>
        <p>No posts</p>
    <?php endif; ?>

<?php 
// ELSE (IF THE USER IS NOT LOGGED IN) DISPLAY MESSAGE
else : ?>
    <p>No posts</p>
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM