返回介绍

have_posts()

发布于 2017-09-11 00:53:42 字数 2451 浏览 1554 评论 0 收藏 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();
}

更新日志

Versiondescription
1.5.0Introduced.

相关函数

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()

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;

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文