问题
I am trying to use the example shown in the Timber docs for pagination with a custom post type. This is not working as I'd expect.
The only way I've gotten a pagination to output is to add query_posts($args);
after I set up my query $args
and before I pass them into a new Timber\PostQuery
but from everything I've read, I shouldn't be doing this.
I have read this issue thread, but it seems to rely on using WP_Query
directly, and I'm trying to keep this task as simple as possible.
Any tips would be appreciated.
回答1:
Well, I can't see where this is documented, but this structure seems to have worked for me (calling pagination()
on my CPT collection):
$args = array(
'post_type' => 'my_custom_post_type',
'posts_per_page' => 5,
'paged' => $paged
);
$myCollection = new Timber\PostQuery($args);
$context['collection'] = $myCollection;
$context['pagination'] = $myCollection->pagination();
Then I have to set up Routes::map for the pagination to actually work. Here's an example:
function add_routes() {
Routes::map(':name/page/:pg', function($params){
$query = 'posts_per_page=1&post_type=page&paged='.$params['pg'];
Routes::load('template-'.$params['name'].'.php', $params, $query);
});
}
I'm calling this function from the root of my functions.php
(i.e., not using any hook).
I should note that this also allows me to still get the page
in my context -- on every paginated page -- using $post = new Timber\Post()
. The key there seems to be setting up the route with posts_per_page=1
and post_type=page
. Originally, I was confusing myself by setting up the route mapping the same as my query $args
for paginated CPTs in my template.
来源:https://stackoverflow.com/questions/53401026/timber-pagination-with-custom-post-type