If value present, order posts by two consecutive custom fields

Why you are using pre_get_posts when using your own get_posts() ? You can just pass the argument list directly to get_posts().

orderby can accept array of arguments and can order by multiple values.
First name the indexes of meta queries array. This can be anything to use in orderby parameter. e.g.

'meta_query' => array(
        'album_title_meta' => array(
            'key' => 'sd_album_title',
            'compare' => 'EXISTS',
        ),
        'album_track_n_meta' => array(
            'key' => 'sd_album_track_n',
            'value' => 'target_value',
            'compare' => '>=',
            'type' => 'numeric'
        )
    ),

Then pass an array in orderby, constructed using these keys!

'orderby' => array(
        'album_title_meta' => 'ASC',
        'album_track_n_meta' => 'DESC',
    ),

First, posts will be order by album title, ASC then track number, DESC.

The complete example:

$my_args = array(
    'post_type' => 'lyric',
    'meta_query' => array(
        'album_title_meta' => array(
            'key' => 'sd_album_title',
            'compare' => 'EXISTS',
        ),
        'album_track_n_meta' => array(
            'key' => 'sd_album_track_n',
            'value' => 'target_value',
            'compare' => '>=',
            'type' => 'numeric'
        )
    ),
    'orderby' => array(
        'album_title_meta' => 'ASC',
        'album_track_n_meta' => 'DESC',
    ),
);
$getlist = get_posts($my_args);

NOTE: these syntax are only supported since WordPress version
4.2

Leave a Comment