Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
1  
Thank you! Out of interest, what does posts_clauses do? –  Squrler Jul 25 '12 at 11:27
    
See edit & update of the answer. –  kaiser Jul 25 '12 at 11:42
    
Amazing, thank you! –  Squrler Jul 26 '12 at 7:31
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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