0

I'm trying to figure out how to get an alphabetically ordered list of posts using two different orderby parameters.

Im filtering the archive query something like this:

function change_sort_order_on_archive() {
  if ( is_archive() AND $query->is_main_query() ) {
    $query->set( 'meta_key', 'my_extra_title_field' );
    $query->set( 'orderby', 'meta_value title' );
    $query->set( 'order', 'ASC' );
  }
add_action( 'pre_get_posts', 'change_sort_order_on_archive');

But the results show posts sorted by meta_field first (A-Z) then shows the rest of the posts (those that don't have the meta field) sorted by title (A-Z). IE two distinct sorted groups of posts.

What i want is one single sorted group of posts (A-Z) that uses the meta field if it exists and otherwise uses the title field to place it in order.

Is it possible or do i have to re-sort my query before printing it to the actual page?

1 Answer 1

0

Try using this syntax below :

$query->set('orderby', array('title' => 'ASC', 'meta_value' => 'ASC'));
// $query->set('order', 'ASC' ); // not needed any more
1
  • Hmm, this produces one sorted group but that is because all posts have a title field, but only some have the meta field. So with this none of the posts are sorted according to the meta field.
    – Kris
    Oct 10, 2018 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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