如果使用默认WP\\U查询,可以在循环中执行以下操作:
if ( have_posts() ) {
global $wp_query;
$paged = !empty($wp_query->query_vars[\'paged\']) ? $wp_query->query_vars[\'paged\'] : 1;
$prev_posts = ( $paged - 1 ) * $wp_query->query_vars[\'posts_per_page\'];
$from = 1 + $prev_posts;
$to = count( $wp_query->posts ) + $prev_posts;
$of = $wp_query->found_posts;
// ... Display the information, for example
printf( \'%s to %s of %s\', $from, $to, $of );
// Then your normal loop
while ( have_posts() ) {
//...
}
}
如果使用自定义查询,可以这样做:
$myquery = new WP_Query($yourqueryargs);
if ( $myquery->have_posts() ) {
$paged = !empty($myquery->query_vars[\'paged\']) ? $myquery->query_vars[\'paged\'] : 1;
$prev_posts = ( $paged - 1 ) * $myquery->query_vars[\'posts_per_page\'];
$from = 1 + $prev_posts;
$to = count( $myquery->posts ) + $prev_posts;
$of = $myquery->found_posts;
// ... Display the information, for example
printf( \'%s to %s of %s\', $from, $to, $of );
// Then your normal loop
while ( have_posts() ) {
//...
}
}
Even better - 创建一个可用于全局$wp\\u查询或任何自定义查询的函数。
function myThemePostsNow ( $query = null ) {
global $wp_query;
if ( isset($query) && !($query instanceof WP_Query) ) {
return; // Cancel if a query has been set and is not a WP_Query instance
}
elseif ( !isset($query) ) {
$query = $wp_query; // If $query is not set, use global $wp_query data
}
if ( ! $query->have_posts() ) {
return; // Cancel if $query don\'t have posts
}
// If we made it here it means we have a WP_Query with posts
$paged = !empty($query->query_vars[\'paged\']) ? $query->query_vars[\'paged\'] : 1;
$prev_posts = ( $paged - 1 ) * $query->query_vars[\'posts_per_page\'];
$from = 1 + $prev_posts;
$to = count( $query->posts ) + $prev_posts;
$of = $query->found_posts;
// Return the information
return sprintf( \'%s to %s of %s\', $from, $to, $of );
}
然后调用你的函数
if ( have_posts() ) {
echo myThemePostsNow();
while ( have_posts() ) {
//...
}
}
或在自定义查询中,如:
if ( $myquery->have_posts() ) {
echo myThemePostsNow();
// Then your normal loop
while ( have_posts() ) {
//...
}
}