显示“没有帖子”如果用户已登录但还没有帖子,Wordpress 中会显示消息

我目前正在使用下面的代码。它显示当前登录用户发布的所有帖子的链接。我想显示“没有帖子”如果当前登录的用户还没有帖子,则显示消息。感谢所有的帮助。


<?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; ?>


明月笑刀无情
浏览 48回答 1
1回答

慕容708150

您需要在&nbsp;中添加另一个&nbsp;if&nbsp;条件来检查当前用户是否有任何帖子。if ( is_user_logged_in() )如果您首先分解想要执行的操作的逻辑,这可以帮助您计划如何编码,例如如果用户已登录:如果他们有帖子则显示帖子否则显示“无帖子”else: 显示“无帖子”现在在您的代码中应用该逻辑:<?php&nbsp;// IF USER IS LOGGED INif ( is_user_logged_in() ):&nbsp;&nbsp; &nbsp; global $current_user;&nbsp;&nbsp; &nbsp; wp_get_current_user();&nbsp; &nbsp; $author_query = array('posts_per_page' => '-1','author' => $current_user->ID);&nbsp; &nbsp; $author_posts = new WP_Query($author_query);&nbsp; &nbsp; // IF THEY HAVE POSTS, DISPLAY THE POSTS&nbsp; &nbsp; if ($author_posts->have_posts()):&nbsp; &nbsp; &nbsp; &nbsp; while($author_posts->have_posts()) : $author_posts->the_post();&nbsp; &nbsp; &nbsp; &nbsp; ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p><a href="<?php the_permalink(); ?>">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<?php the_title(); ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="date"><?php the_time('F j, Y'); ?></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a></p>&nbsp; &nbsp; &nbsp; &nbsp; <?php endwhile; ?>&nbsp; &nbsp; <?php&nbsp;&nbsp; &nbsp; // ELSE (IF THEY HAVE NO POSTS) DISPLAY MESSAGE&nbsp; &nbsp; else : ?>&nbsp; &nbsp; &nbsp; &nbsp; <p>No posts</p>&nbsp; &nbsp; <?php endif; ?><?php&nbsp;// ELSE (IF THE USER IS NOT LOGGED IN) DISPLAY MESSAGEelse : ?>&nbsp; &nbsp; <p>No posts</p><?php endif; ?>
打开App,查看更多内容
随时随地看视频慕课网APP