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 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.

<?php
add_filter('posts_orderby', 'orderby_last_modified');
if(have_posts()):
while(have_posts()) atom()->template('teaser');
remove_filter('posts_orderby', 'orderby_last_modified');
?>
share|improve this question

1 Answer 1

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

 
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.