1

I am using Timber to develop a WordPress theme, and am using Routing to allow me to filter an archive of posts by the field name and value (as added using Advanced Custom Fields.

My routing looks like this:

<?php

Routes::map('items/:field/:value', function($params) {

  $query = array(
    'post_type' => 'item',
    'meta_key' => $params['field'],
    'meta_value' => $params['value']
  );

  Routes::load('archive-item.php', $params, $query);
});

...and my archive looks like this:

<?php

global $params;

$context = Timber::get_context();
$context['items'] = Timber::get_posts();
$context['params'] = $params;

Timber::render('item/archive.twig', $context);

This is working as I'd hope - if I add two parameters to my URL (the field name and the value) I get the posts that match the query.

My issue is: I want to add pagination to this and I'm not sure how.

  • If I add /page/:page_no to the routing it gives me a 404 if these parameters aren't included in the URL. Can these parameters be marked as optional in some way?
  • I'd like to be able to paginate this same view without using the parameters I've added in my routing (unfiltered). So the /page/x would be on the URL without the other parameters.
  • Using Timber::get_pagination() seems to conflict with my routing (or vice versa), giving me 404 errors.

I can't find anything documented to solve this. Is there a way to do it?

1

After some messing around (and actually looking at the docs properly!) I have solved the problem. In my routing, I just need to add another map to handle paging with my custom routing:

Routes::map('items/browse/:field/:value', function($params) {
  $query = array(
    'post_type' => 'item',
    'meta_key' => $params['field'],
    'meta_value' => $params['value']
  );
  Routes::load('archive-item.php', $params, $query);
});


Routes::map('items/browse/:field/:value/page/:page', function($params) {
  $query = array(
    'post_type' => 'item',
    'meta_key' => $params['field'],
    'meta_value' => $params['value'],
    'paged' => $params['page']
  );
  Routes::load('archive-item.php', $params, $query);
});
  • Thanks for sharing, I might need that in a future project :) – Luckyfella Aug 2 '17 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.