Wordpress 如何检查查询是否有帖子

Wordpress how to check if a query has posts

此代码允许我向连接的用户显示他所写文章的列表。但是,我想选择在没有文章被写入时(列表为空时)出现的消息。

我知道我需要一个 IF 语句,但我真的不知道把它放在哪里以及用什么数据。

我想让没有文章的用户看到“没有文章”写的。

提前致谢,

这是我的代码:

add_action( 'woocommerce_account_dashboard' , 'recent_posts', 3 );
function recent_posts() {
    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);
    ?><div id="recentposts">
            
    <ul class="liststylenone">
        
    <?php
    while($author_posts->have_posts()) : $author_posts->the_post();
    ?>
            <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>   
    <?php           
    endwhile;
    ?></ul><?php
else :
    echo "not logged in";
endif;

?>

当您使用 wp_query 时,它有一个名为 found_posts 的 属性。在您的 ul 标记之前,我们将检查您的查询中是否有任何 post。如果没有找到 post,那么我们将回显带有消息的 p 标记。像这样:

add_action('woocommerce_account_dashboard', 'recent_posts', 3);

function recent_posts()
{
  if (is_user_logged_in()) :

    global $current_user;

    $author_query = array('posts_per_page' => '-1', 'author' => $current_user->ID);

    $author_posts = new WP_Query($author_query);

?>
    <div id="recentposts">
      <?php
      if ($author_posts->found_posts) {
      ?>
        <ul class="liststylenone">
          <?php
          while ($author_posts->have_posts()) : $author_posts->the_post();
          ?>
            <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
          <?php
          endwhile;
          ?>
        </ul>
  <?php
      } else {
        echo '<p class="author-no-post-yet">No Articles</p>';
      }
    else :
      echo "not logged in";
    endif;
}