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:


while (have_posts()) : the_post();

Template code here



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


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' );
  • Thanks for this link and details Never use quer_post @Milo – jas Jan 22 '16 at 17:39
  • Awesome! Thanks for your help, this was the solution for me! – Moose Jan 22 '16 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.