我创建了一个帖子以显示书籍列表。 我添加了一个计数器来显示这本书的排名。
这是分页的帖子,每页10个帖子。当我转到下一页时,计数器不断返回原始编号。
例如:
Page 1 - 100, 99, ... 91
Page 2 - 100, 99, ... 91
...
Page 10 - 100, 99, ... 91
我希望计数器正常运行,显示 100-1 。
这是我正在使用的代码:
<?php
$postidsstring = get_field('post_ids_to_be_included');
$postidsarray = explode(", ",$postidsstring);
$countposts = count($postidsarray);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'books',
'post__in' => $postidsarray,
'orderby' => 'post__in',
'numberposts' => -1,
'paged' => $paged,
'posts_per_page' => 10
);
$myposts = new WP_Query( $args );
$total_pages = $myposts->max_num_pages;
if ( $myposts->have_posts() ) :
while ( $myposts->have_posts() ) : $myposts->the_post(); ?>
<?php echo $countposts; ?>. <?php the_title(); $countposts--; ?>
//Other details
<br>
<?php endwhile;
if ($total_pages > 1) :
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text'=> __('« prev'),
'next_text'=> __('next »'),
));
endif;
endif;
wp_reset_postdata();
?>
如何纠正此问题?
编辑:我正在使用此代码来防止重定向到function.php中的页面1:
add_action( 'template_redirect', function() {
if ( is_singular( 'list' ) ) {
global $wp_query;
$page = ( int ) $wp_query->get( 'page' );
if ( $page > 1 ) {
// convert 'page' to 'paged'
$query->set( 'page', 1 );
$query->set( 'paged', $page );
}
// prevent redirect
remove_action( 'template_redirect', 'redirect_canonical' );
}
}, 0 );
答案 0 :(得分:0)
我找到了一个解决方案,尽管不确定它是否正确,但这对我有用。我添加了另一个计数器,该计数器将使用变量countposts,current_page和posts_per_page中的值来显示正确的计数器。就是这样:
<?php
$postidsstring = get_field('post_ids_to_be_included');
$postidsarray = explode(", ",$postidsstring);
$countposts = count($postidsarray);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'books',
'post__in' => $postidsarray,
'orderby' => 'post__in',
'numberposts' => -1,
'paged' => $paged,
'posts_per_page' => 10
);
$myposts = new WP_Query( $args );
$total_pages = $myposts->max_num_pages;
if ( $myposts->have_posts() ) :
$current_page = max(1, get_query_var('paged'));
while ( $myposts->have_posts() ) : $myposts->the_post();
$counter = $countposts-(($current_page-1)*$posts_per_page); ?>
<?php echo $counter; ?>. <?php the_title(); $countposts--; ?>
//Other details
<br>
<?php endwhile;
if ($total_pages > 1) :
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text'=> __('« prev'),
'next_text'=> __('next »'),
));
endif;
endif;
wp_reset_postdata();
?>
我从旧的blog post获得了此解决方案。