How to use pre_get_posts?

Remove all query code from the template and just leave the default loop. In your example code you’re overwriting the query in the template, in the code you pasted in the comments, you’re running an entirely new query. These are both unnecessary when using pre_get_posts.

Put your pre_get_posts code in functions.php. You don’t have to pass $paged or do anything fancy except set the specific parameters you want to modify, this code is running before the query happens:

function pregp_wpse_102658( $qry ) {
    if ( $qry->is_main_query() && $qry->is_category( 'expiresoon' ) ) {
        $qry->set('meta_key','hmeromhnia_lhkshs');
        $qry->set('orderby','meta_value_num');
        $qry->set('order','ASC');
        $qry->set('posts_per_page',9);
    }
}
add_action('pre_get_posts','pregp_wpse_102658');

and then just use the plain vanilla loop in the template:

if ( have_posts() ) :
    while ( have_posts() ) : the_post();  
        // The Loop
    endwhile;
endif;

If there is nothing else special about this particular category, you no longer need a category template specific to that one category, since the query modification now happens outside the template.

Leave a Comment