我无法找到如何在wordpress中为自定义循环添加分页的明确答案。根据我从codex的理解,我应该使用get_posts()(或者我错了,我应该使用WP_Query或query_posts?)
假设我有自定义帖子类型entry
宽度分类entry_cat
,我想显示类别为cat-1
或cat-2
的内容并添加分页。
我的代码主要有效:
<?php
$pageda = get_query_var('paged') ? get_query_var('paged') : 1;
$posts_per_page = get_option('posts_per_page');
$post_offset = ($pageda - 1) * $posts_per_page;
$args = array(
'numberposts' => $posts_per_page,
'post_type' => 'entry',
'offset' => $post_offset,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'entry_cat',
'field' => 'slug',
'terms' => 'cat-1',
),
array(
'taxonomy' => 'entry_cat',
'field' => 'slug',
'terms' => 'cat-2',
),
),
);
$posts=get_posts($args);
$args['numberposts'] = -1;
$posts_count=count(get_posts($args));
if($posts):
foreach($posts as $post):
?>
<?php the_title() ?><br />
<?php
endforeach;
endif;
echo paginate_links(array(
'current' => $pageda,
'total' => ceil($posts_count / $posts_per_page),
));
?>
但我有两个问题。
我是否正确地解决了这个问题?如果没有,那么最佳选择是什么?
答案 0 :(得分:0)
比在WordPress中使用wp-pagenavi插件和自定义查询更好,例如这个问题与wp-pagenavi插件:
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$myquery = new WP_Query(
array(
'posts_per_page' => '2',
'paged'=>$paged
// add any other parameters to your wp_query array
)
);
?>
<?php
if ($myquery->have_posts()) : while ($myquery->have_posts()) : $myquery->the_post();
?>
<!-- Start your post. Below an example: -->
<div class="article-box">
<h2 class="article-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="article-excerpt"><?php echo(get_the_excerpt()); ?></p>
</div>
<!-- End of your post -->
<?php endwhile; ?>
<?php wp_pagenavi( array( 'query' => $myquery ) ); ?><!-- IMPORTANT: make sure to include an array with your previously declared query values in here -->
<?php wp_reset_query(); ?>
<?php else : ?>
<p>No posts found</p>
<?php endif; ?>