add_filter() doesn’t work in loop

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:

Read More
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');
?>

Related posts

Leave a Reply

1 comment

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