have_posts() - WordPress 函数参考中文文档

返回介绍

have_posts()

发布于 2017-09-11 字数3017 浏览 1031 评论 0

have_posts()

Whether current WordPress query has results to loop over.


描述


返回值

(bool)


源代码

File: wp-includes/query.php

function have_posts() {
	global $wp_query;
	return $wp_query->have_posts();
}

更新日志

Version 描述
1.5.0 Introduced.

相关函数

Uses

  • wp-includes/class-wp-query.php:
    WP_Query::have_posts()

Used By

  • wp-admin/includes/class-wp-media-list-table.php:
    WP_Media_List_Table::has_items()
  • wp-admin/includes/class-wp-media-list-table.php:
    WP_Media_List_Table::display_rows()
  • wp-admin/includes/class-wp-posts-list-table.php:
    WP_Posts_List_Table::has_items()

User Contributed Notes

  1. Skip to note content

    You must log in to vote on the helpfulness of this noteVote results for this note: 3You must log in to vote on the helpfulness of this note

    Contributed by Codex

    Avoiding infinite loops:
    Calling this function within the loop will cause an infinite loop. For example, see the following code:

    
    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;
    

    If you want to check if there are more posts in the current loop without this unfortunate side effect, you can use this function:

    In your functions.php file:

    
    /**
     * 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;
    }
    

    In your template file:

    
    while ( have_posts() ) : the_post();
        // Display post
        if ( wpdocs_has_more_posts() ) :
            // Do something if this isn't the last post
        endif;
    endwhile;
    
  2. Default use:
    The following example can be used to determine if any posts exist and loop through them if they do.

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

上一篇:have_comments()

下一篇:header_image()

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

目前还没有任何评论,快来抢沙发吧!