Support

Account

Home Forums General Issues Pre Get Posts Query – Sort results 2 meta Fields

Solved

Pre Get Posts Query – Sort results 2 meta Fields

  • I am trying to sort custom posts using two meta fields ‘surname’ and ‘forenames’. The documentation is confusing me and I hope someone can help.

    Here’s the code I have so far, which sorts the surname field:
    function my_pre_get_posts( $query ) {

    // do not modify queries in the admin
    if( is_admin() ) {

    return $query;

    }

    // only modify queries for ‘individuals’ post type
    if( isset($query->query_vars[‘post_type’]) && $query->query_vars[‘post_type’] == ‘individuals’ ) {

    $query->set(‘orderby’, ‘meta_value’);
    $query->set(‘meta_key’, ‘surname’);
    $query->set(‘order’, ‘ASC’);

    }

    // return
    return $query;

    }

    add_action(‘pre_get_posts’, ‘my_pre_get_posts’);

    How do I need to amend it?

    Manny thanks

  • Similar question here: https://support.advancedcustomfields.com/forums/topic/order-cpt-by-date-picker-then-by-time-picker/

    The only difference is that you set the meta_query and orderby values instead of what you’re doing.

  • Thanks John, though I don’t understand enough to know how to adapt my code. Is there a simple couple of lines I can add?

  • 
    $meta_query = array(
      'relation' => 'AND',
      'date_clause' => array(
          'key' => 'date_field_name',
          'compare' => 'EXISTS'
       ),,
      'time_clause' => array(
          'key' => 'time_field_name',
          'compare' => 'EXISTS'
       ),
    );
    $query->set('meta_query', $meta_query);
    $orderby = array(
      'date_clause' => 'ASC',
      'time_clause' => 'ASC'
    );
    $query->set('orderby', $orderby); 
    
  • Thank you John, I think I now understand what the query is doing.. However I’m getting an error which suggests the arrays are incorrect? See the error at the bottom of the image:

  • double comma on line 45

  • Thank you John, that works perfectly!

    As a follow up, If I filter the posts by surname, the results are no longer in ascending order by forenames.. Does this mean I have to find a separate means of targeting the filtered results?

Viewing 7 posts - 1 through 7 (of 7 total)

The topic ‘Pre Get Posts Query – Sort results 2 meta Fields’ is closed to new replies.