Ordering CPT Archive by Custom Fields

Helpful when you need to set the default sort order of your custom post type archives based on values of custom fields within that post type.

Helpful when you need to override the default order of a Post Archive. You can easily modify this for your Custom Post Type by changing out the cpt_name  and custom_field  to apply to your particular situation.

<?php
  function slug_order_archive_by_field( $query ) {
      //Only do if is main query fo a specific cpt's archive.
      if ( $query->is_main_query() &&  

          //@TODO set cpt's name
          is_post_type_archive( 'CPT_NAME' ) ) {

          //@TODO Set the name of the field we are ordering by
          $query->set( 'meta_key', 'FIELD_NAME' );
          
          //@TODO change order to DESC IF you want to go in reverse order
          $query->set( 'order', 'ASC' );

          //@TODO uncomment next line IF you want to sort by an integer instead of alphabetically
          //$query->set( 'orderby', 'meta_value_num' );

          //@TODO uncomment next line IF your sort is based on DATE instead 
          //$query->set( 'orderby', 'meta_value_date' );
      }
  }
  add_action( 'pre_get_posts', 'slug_order_archive_by_field' );
?>

Reorder a WordPress custom post type archive page by the value of a meta field. Based on this SE answer: http://wordpress.stackexchange.com/a/48658/25300

Questions