Sort by meta key on archive page

I am trying to sort an archive page using a meta key value (which happens to be a Unix timestamp). Currently I have the posts listed on the page by their WordPress creation date. I want to use the meta key – which is a different date than the WP creation date.

The code is pretty simple at this point, its just using The Loop to display the posts using a template:

<?php

while (have_posts()) : the_post();


Template code here


endwhile;

?>

How do I get the posts to show up by the meta value dates instead of the WP creation date?

1 Answer
1

Use pre_get_posts to alter the main query before it is run. The action runs on every query, use the Conditional Tags to target specific queries.

function wpd_sort_by_meta( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'meta_key', 'your_meta_key' );
        $query->set( 'orderby', 'meta_value_num' );
    }
}
add_action( 'pre_get_posts', 'wpd_sort_by_meta' );

Leave a Comment