I need a list of posts of a specific post_type plus the name of a custom taxonomy term.

This is what I got so far

SELECT p.post_name,t.name as clientName 
FROM $wpdb->posts AS p, $wpdb->terms AS t
LEFT JOIN $wpdb->term_relationships AS tr ON ('p.ID' = tr.object_id)
LEFT JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
LEFT JOIN $wpdb->terms AS t2 ON (t2.term_id = tt.term_id)
WHERE   p.post_status="publish" 
    AND p.post_type="portfolio"
    AND tt.taxonomy = 'clients' 
ORDER BY p.post_date DESC

What´s the problem?
I´m getting too many results, I get the right posts, but several times with every client.
I guess thats because I use $wpdb->terms as t AND as t2?
But when I try to use it as t both times I get the error

Not unique table/alias: 't'

Who can help?

1
1

Sorry guys, I just found the solution:

SELECT p.post_name, t.name as clientName 
FROM $wpdb->posts AS p
INNER JOIN $wpdb->term_relationships AS tr ON ('p.ID' = tr.object_id)
INNER JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
INNER JOIN $wpdb->terms AS t ON (t.term_id = tt.term_id)
WHERE   p.post_status="publish" 
    AND p.post_type="portfolio"
    AND tt.taxonomy = 'clients' 
ORDER BY p.post_date DESC

I just don’t have to define an alias for $wpdb->terms in FROM clause.

Tags:

Leave a Reply

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