skip to Main Content

enter image description hereI’m trying to query all posts from my WordPress site that have wp_terms.slug = ‘portfolio-photos’. I’ve connected the tables using wp_terms, wp_term_taxonomy, wp_term_relationships and wp_posts. I’m not sure what’s wrong with the SQL code I have. Can someone advise what’s wrong with my code/train of thought on this?

I receive 0 rows, however, there should be 12 rows because that’s how many I have in WP with the “portfolio-photos” slug. The column headers are ID, term_id, and slug.

SELECT wp_posts.ID, wp_terms.term_id, wp_terms.slug
FROM wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
LEFT JOIN wp_terms ON (wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id)
WHERE wp_terms.slug = 'portfolio-photos'

2

Answers


  1. Chosen as BEST ANSWER

    I realized I had the correct code after carefully looking at how the tables in the WP DB relate. This article really helped. I was trying to pull up results using a slug that corresponded with the parent category.

    Therefore, my original code above only worked for sub-categories. This code below pulls up the correct amount of results by using WHERE wp_term_taxonomy.parent = '11'

    SELECT wp_posts.ID, wp_terms.term_id, wp_term_taxonomy.parent, wp_terms.slug
    FROM wp_posts
    LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
    LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
    LEFT JOIN wp_terms ON (wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id)
    WHERE wp_term_taxonomy.parent = '11'
    

  2. The table wp_terms is nowhere in your FROM clause, you’d have to relate it to use it in your WHERE clause.

    EDIT: Original post was changed after my original answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search