0

I have a custom post type named Faculty. They can be any of the type MCT, MLT, or MT.

MCT -> A, B 
MLT -> C, E 
MT  -> C, D

I want to list all MLT and MT faculty on a page in order by last name -> C, D, E

I am having a problem with the OR relation when used with orderby where it is returning all faculty that are MLT or MT or have a last name (which is everyone). The AND relation works correctly, returning just C.

My WP_Query arguments are:

Array(
    [post_type] => faculty
    [order] => ASC
    [orderby] => meta_value
    [meta_key] => faculty_last_name
    [meta_query] => Array(
            [relation] => OR
            [0] => Array(
                    [key] => faculty_MLT
                    [value] => MLT
                    [compare] => =
                )   
            [1] => Array(
                    [key] => faculty_MT
                    [value] => MT
                    [compare] => =
                )
        )    
)

The SQL created is:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id INNER JOIN wp_postmeta AS mt1 
ON (wp_posts.ID = mt1.post_id) 
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id) 
WHERE 1=1 AND wp_posts.post_type = 'faculty' AND (wp_posts.post_status = 'publish' 
OR wp_posts.post_status = 'private') 
AND (wp_postmeta.meta_key = 'faculty_last_name' 
-->OR (mt1.meta_key = 'faculty_MLT' AND CAST(mt1.meta_value AS CHAR) = 'MLT') 
OR (mt2.meta_key = 'faculty_MT' AND CAST(mt2.meta_value AS CHAR) = 'MT') ) 
GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value ASC LIMIT 0, 10

If I change the -->OR to AND, the query returns the correct result.

Is there some way to use orderby along with relation => OR in wp_query?

0

This is a little hard to tinker with, without data to try it on.

What strikes me as strange in your architecture that you describe it as type with three possible values, but what you have it three (I guess) different keys for it. It would make more sense to me if you had single key (say faculty_type).

As it is my best guess would be try to reverse it and condition that faculty is not the remaining third type instead. Not clear if you have any entries that aren't in any faculty though.

  • I need multiple keys because a faculty can be multiple types. Some are both MLT and MT like 'C' in my example. I will try the NOT although I actually have 4 types so I may have the same problem. – Emily Oct 24 '15 at 16:20
  • Hm, then it sounds more like taxonomy than custom field to me. But it's always hard to look at such things going by quick description alone. – Rarst Oct 24 '15 at 16:23

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.