当前浏览:首页 / WordPress函数 / have_posts()

have_posts()

确定当前WordPress查询是否有要循环的文章

postsmore...


返回

(bool) 如果有文章,则为True,如果循环结束,则为false。


说明

此函数检查主WP_Query对象中是否有更多可用的文章要循环。它调用全局$wp_query对象上的have_posts()方法。

如果循环中没有更多文章,它将触发loop_end动作,然后调用rewind_posts()方法



源码

查看源码 官方文档


更新日志

版本描述
1.5.0开始引入

使用示例

  • 示例1

    默认用法:以下示例可用于确定是否存在任何文章,如果存在,则执行循环。

    if ( have_posts() ) :
        while ( have_posts() ) : the_post();
            // Your loop code
        endwhile;
    else :
        _e( 'Sorry, no posts were found.', 'textdomain' );
    endif;
    
  • 示例2

    避免无限循环:在循环内调用此函数将导致无限循环。例如,请参见以下代码:

    while ( have_posts() ) : the_post();
        // Display post
        if ( have_posts() ) : // If this is the last post, the loop will start over
            // Do something if this isn't the last post
        endif;
    endwhile;
    

    如果您想检查当前循环中是否有更多文章而没有这种副作用,可以使用此函数:

    functions.php文件中:

    /**
     * Check if a loop has any more posts left.
     *
     * @global $wp_query
     *
     * @return bool True if there are any more posts in this loop, false if not.
     */
    function wpdocs_has_more_posts() {
      global $wp_query;
      return $wp_query->current_post + 1 < $wp_query->post_count;
    }
    

    在模板文件中:

    while ( have_posts() ) : the_post();
        // Display post
        if ( wpdocs_has_more_posts() ) :
            // Do something if this isn't the last post
        endif;
    endwhile;
    
  • 示例3
    <?php if ( have_posts() ) : while( have_posts()  ) : the_post(); ?>
        <h1><?php the_title(); ?></h1>
        <a href="<?php the_permalink(); ?>">
            <?php the_post_thumbnail( 'full' ); ?>
        </a>
        <p><?php the_excerpt(); ?></p>
    <?php endwhile; endif; ?>
    

    输出:
    文章标题
    文章特色全尺寸图像(当任何人点击图像后打开文章单页)
    文章小说明

    Edited by @audrasjb: Small WPCS fixes.

  • 示例4

    示例:如果在标准WP循环上下文外创建自定义WP_Query。本例使用从WP_Query扩展而来的have_posts()函数:

    <?php
    // Define args
    $args = array('post_type' => 'custom_post_type');
    
    // Execute query
    $cpt_query = new WP_Query($args);
    
    // Create cpt loop, with a have_posts() check!
    if ($cpt_query->have_posts()) :
      while ($cpt_query->have_posts()) : $cpt_query->the_post(); ?>
    
        <?php the_title(); ?>
    
    <?php endwhile;
    endif; ?>