0

I'm currently sorting some posts out by custom fields 'role' and 'surname', using the following:

function customorder($orderby) {
    return 'mt1.meta_value DESC, mt2.meta_value ASC';
}

$args = array(
    'post_type'     => 'staff', 
    'meta_key'      => 'role',
    'meta_query'    => array(
        array(
        'key' => 'role'
        ),
        array(
        'key' => 'surname',
        ),
    )
);

add_filter('posts_orderby','customorder');
$query = new WP_Query( $args );
remove_filter('posts_orderby','customorder');

How can I define the order that I would like the first meta_key in, as opposed to alphabetically desc or ascending. For example where role = 'Head Teacher', 'Deputy', 'Teacher', 'Support', 'Clerical' ... etc Therefor grouping the posts by the meta_key value.

Thanks in advance for any help

Cheers

Noel

1

You can use FIELD or FIND_IN_SET:

return "FIELD(mt1.meta_value, 'Head Teacher', 'Deputy', 'Teacher', 'Support', 'Clerical') ASC, mt2.meta_value ASC";

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field

  • Cheers, that worked perfectly. I couldn't figure out how I needed to approach this. Thanks a million. – noelmcg Aug 9 '14 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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