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');
?>
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:
This would go in your
functions.php
along with yourorderby_last_modified
function.See the WordPress Action Reference for the order actions are executed in a request.