6

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?

4
  • Use WP_Query. Cannot see why you need to run a custom SQL query Commented Apr 20, 2016 at 9:00
  • @Pieter: Hmm ok, how would that look like? Would it be possible with WP_Query to filter by two taxonomies as well? As I need to filter for "language" taxonomy created by the Polylang Plugin Commented Apr 20, 2016 at 9:06
  • Have you read this Commented Apr 20, 2016 at 9:08
  • 1
    Yeah thanks, but that won´t give me the name of the taxonomy in one go, right? I´d have to make a wp_get_post_terms() for each post again, which sums up to alot of queries I guess? Commented Apr 20, 2016 at 11:39

1 Answer 1

7

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.

1
  • 1
    Need to remove the single quotes from around p.ID
    – CragMonkey
    Commented Apr 21, 2018 at 2:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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