I have a query to select posts (wp_posts table
) where either 1 key/value pair or another is present on the a second table (wp_postmeta
). Esentially, this works, but I then need to order the results by the first key/pair value (department_head
), and then the second (staff_surname
).
The problem is, becuause of the way the results are grabbed by the query, there is no department_head
key to use to order the results by. I'm guessing that this is because the query is finding the staff_surname
key first?
Again guessing, but if my above guess is correct then it is because, even though I'm joining the table twice, MYSQL is just grabbing the first instance from the wp_postmeta
table when the staff_surname
condition is met. This is what I need to find away around, so that I have the correct data to be able to order the results.
Full query -
SELECT SQL_CALC_FOUND_ROWS wp_posts.*
FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
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)
WHERE 1=1
AND (
wp_term_relationships.term_taxonomy_id IN (34)
)
AND wp_posts.post_type = 'people'
AND (
wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'private'
)
AND (
(
wp_postmeta.meta_key = 'department_head'
AND CAST(wp_postmeta.meta_value AS CHAR) = 'private-client'
)
OR (
mt1.meta_key = 'staff_surname'
AND CAST(mt1.meta_value AS CHAR) != ''
)
)
GROUP BY wp_posts.ID
ORDER BY mt1.meta_value ASC
LIMIT 0, 10
Example of query results -
ID name meta_id post_id meta_key meta_value meta_id post_id meta_key meta_value
1 Test1 10 1 random_key random_value 11 1 staff_surname Smith
2 Test1 20 2 random_key random_value 21 2 staff_surname Jones
3 Test1 30 3 random_key random_value 31 3 staff_surname Harris
Example of what I require, if Jones was the department head -
ID name meta_id post_id meta_key meta_value meta_id post_id meta_key meta_value
1 Test1 10 1 11 1 staff_surname Smith
2 Test1 22 2 department_head private-client 21 2 staff_surname Jones
3 Test1 30 3 31 3 staff_surname Harris
The 'department_head' key does not exist in the vast majority of cases, that is why the key/value are blank on the other resutes.
Is there a way to achieve the ordering results that I require?
Note: The reason that I have posted this here as opposed to the Wordpress site is because this is a custom query, not WP generated, so it will likely be out of the scope of most WP experts.