1

I'm using a custom loop to display posts using pagination. My query shows 4 posts per page, and there are 4 pages, so 16 posts in total. Is it possible to load in the last page of posts first? So when I load the query, it first shows page 4, then when I click 'show next' it shows page 3, et cetera?

1 Answer 1

2

Is it possible to load in the last page of posts first?

Order DESC instead of ASC and make use of the posts_clauses filter.

function wpse_59557_order_desc( $pieces ) 
{
    // Add conditionals here and abort in cases, where we don't want this, for e.g.:
    // if ( ! is_home() OR ! is_front_page() ) return;

    // We only want if to run once
    remove_filter( current_filter(), __FUNCTION__ );

    return $pieces['orderby'] = 'DESC';
}
add_filter( 'posts_clauses', 'wpse_59557_order_desc' );

Explanation

The posts_clauses is the last filter in a series of filters (for e.g. posts_where), that allow the manipulation of the current query. If summons all tasks, the previous filters do: Modify the where/order/orderby/etc. pieces of the sql query. This filter allows a detailed modification of a default core query, and therefore helps avoiding another query for a single task.

When to use it

If you're in need of doing a task, that isn't possible by default and would bring you in the situation where you are about dismissing the first query and adding another one, then this filter can be used.

What to consider

This filter triggers for a lot of stuff. So always make sure to abort this filter in cases, where the modification is not needed/wanted. I also added a call to remove_filter() to avoid intercepting the query more than once. If you want, you can move the conditionals out of the function and wrap the add_filter() call in conditionals.

2
  • 1
    Thank you! Out of interest, what does posts_clauses do?
    – Squrler
    Jul 25, 2012 at 11:27
  • See edit & update of the answer.
    – kaiser
    Jul 25, 2012 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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