为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
明月笑刀无情 2023-12-15 15:23:58
我目前正在使用下面的代码。它显示当前登录用户发布的所有帖子的链接。我想显示“没有帖子”如果当前登录的用户还没有帖子,则显示消息。感谢所有的帮助。<?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; ?>
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

您需要在 中添加另一个 if 条件来检查当前用户是否有任何帖子。if ( is_user_logged_in() )

如果您首先分解想要执行的操作的逻辑,这可以帮助您计划如何编码,例如

  • 如果用户已登录:

    • 如果他们有帖子则显示帖子

    • 否则显示“无帖子”

  • else: 显示“无帖子”

现在在您的代码中应用该逻辑:

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


查看完整回答
反对 回复 2023-12-15
  • 1 回答
  • 0 关注
  • 44 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信