Support

Account

Home Forums Front-end Issues Custom Post Type: Order posts by a group's field at archive page Reply To: Custom Post Type: Order posts by a group's field at archive page

  • This should work with something like:

    
    $args = array(
            'post_type' => 'your_custom_post_type',
            'meta_key'=> 'your_field_date',
            'orderby' => 'meta_value',
            'order' => 'ASC' 
        );
    

    If you’re are working with the archive page, maybe a best way to do it is modify the main query with the pre_get_posts hook.

    For Example:

    
    // in your functions.php
    function sort_by_date_my_cpt( $query ) {
       if ( is_post_type_archive( 'your_custom_post_type') ) {
          $query->set('meta_key', 'your_date_custom_field');
          $query->set('orderby', 'meta_value');
          $query->set('order', 'ASC');
          return;
       }
    }
    add_filter( 'pre_get_posts', 'sort_by_date_my_cpt', 1);
    

    So then, you will to use your WP Loop by default in your archive template.

    
    // in your archive-your_custom_posttype.php or archive.php
    <?php if ( have_posts() ) :
       <?php while ( have_posts() ) : the_post(); ?>
       <?php endwhile; ?>
    <?php endif; ?>