JWDev
JWDev

Reputation: 856

How to inner join from another table and order by specific row value?

In WordPress, there are 2 tables: wp_terms and wp_termmeta.

I currently do the following to get the terms and parents etc:

$query = mysqli_query($mysqli, "
SELECT wp_terms.term_id,wp_terms.name, wp_term_taxonomy.parent
FROM wp_terms INNER JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'post-categories'
ORDER BY name"); 

However - I need to access the wp_termmeta table, select a row where the term_id is the same and the meta_key is "order" then order by the meta_value of the wp_termmeta, instead of name as it is currently.

How would I do that with the current query?

Upvotes: 0

Views: 477

Answers (1)

Tobias Xy
Tobias Xy

Reputation: 2069

I don't have wordpress-specific knowledge, but according to your description the query could look like this (I added table aliases for readability, but they are not necessary):

SELECT t.term_id, t.name, tax.parent
FROM wp_terms t
INNER JOIN wp_term_taxonomy tax ON t.term_id = tax.term_id
INNER JOIN wp_termmeta m ON m.term_id = t.term_id AND m.meta_key = 'order'
WHERE tax.taxonomy = 'post-categories'
ORDER BY m.meta_value

The most interesting part here is the join condition of the second join, which contains two conditions: m.term_id = t.term_id AND m.meta_key = 'order' It first makes sure the term ids are matching and then assures that the meta key of the joined row is actually "order".

Upvotes: 1

Related Questions