Sort posts in WordPress by 2 custom fields

So WordPress doesn’t have a way to sort posts by 2 custom fields. I tried different solutions for this option on the internet but never found anything that was working. So i made a custom hack based on a solution i found on internet.

This solution workes for WordPress 5.X at least.

function orderbyreplace($orderby) {
    global $table_prefix;
    return str_replace($table_prefix.'posts.menu_order', $table_prefix.'postmeta.meta_value, mt1.meta_value', $orderby); // Here you can add also after the meta_value DESC or ASC depending on how you wish the sort
}
$args = array(
  'post_type'=>'posts',
  'orderby' => 'menu_order',
  'order' => 'ASC',
  'meta_query' => array(
        array(
            'key' => 'lastname',
            'value' => '',
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'firstname',
            'value' => '',
            'compare' => 'LIKE'
        )
    )
);

add_filter('posts_orderby','orderbyreplace');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','orderbyreplace');

This solution will sort posts by lastname and firstname custom name.

Leave a Reply

Your email address will not be published. Required fields are marked *