WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to order the posts in the home page by modified date, and I put this code in the functions.php of my active child theme:

function orderby_last_modified() {
  return 'post_modified DESC';

If I add the filter in the same functions.php file it works:

add_filter('posts_orderby', 'orderby_last_modified');

But I only want the filter in the home page loop, when I change that line to the home page it just dont work.

add_filter('posts_orderby', 'orderby_last_modified');
while(have_posts()) atom()->template('teaser');
remove_filter('posts_orderby', 'orderby_last_modified');
share|improve this question
up vote 3 down vote accepted

It doesn't work in your template because the query has already happened before the template is loaded. If you want to add your filter only under certain conditions, you need to hook an earlier action, like pre_get_posts, and check if the query is for the home page:

function add_my_orderby_filter( $query ) {
    if ( $query->is_home ) {
        add_filter('posts_orderby', 'orderby_last_modified');
add_action( 'pre_get_posts', 'add_my_orderby_filter' );

This would go in your functions.php along with your orderby_last_modified function.

See the WordPress Action Reference for the order actions are executed in a request.

share|improve this answer
Yeah Its exactly what I have done some time ago and its working perfect, the only difference is that I use is_home(), thanks anyways. – Shixons Feb 2 '12 at 5:17

Your Answer


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.