要获取WordPress中的文章总数,您可以使用WP_Query
类或query_posts
函数。以下是使用query_posts
函数获取文章总数的示例代码:
<?php // 保存当前的查询参数 $temp_query = $wp_query; // 设置新的查询参数 query_posts('post_type=post&posts_per_page=-1'); // 获取文章总数 $total_posts = $wp_query->found_posts; // 恢复之前的查询参数 $wp_query = $temp_query; wp_reset_query(); // 输出文章总数 echo '文章总数:' . $total_posts; ?>
上述代码中,query_posts
函数用于设置新的查询参数,其中post_type=post
表示查询文章类型为普通文章,posts_per_page=-1
表示获取所有文章(不分页)。然后,通过$wp_query->found_posts
获取文章总数。
请注意,query_posts
函数会修改全局的$wp_query
对象,因此在使用之前需要保存当前的查询参数,并在获取文章总数后恢复之前的查询参数。最后,通过wp_reset_query
函数重置查询参数,以确保不会影响其他查询。
如果您想更灵活地控制查询参数,建议使用WP_Query
类进行文章查询。
- 本文来源链接地址: https://www.npspro.cn/8926.html