【发布时间】:2017-04-14 22:41:46
【问题描述】:
对于如何在 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),
));
?>
但我有两个问题。
- 不能用于首页。
- 它从数据库中获取帖子两次只是为了计算它们。 有没有一种功能可以让我在不查询组合分类法的情况下检查帖子的数量?
我是否正确地解决了这个问题?如果没有,最好的选择是什么?
【问题讨论】:
标签: php wordpress pagination