Wordpress JOIN wp_post and wp_postmeta

11,000

Based on the link mentioned above, I was able to create this pattern to search custom posts_types based on 3 meta_values and 1 custom taxonomy.

So my structure is:

  1. Each custom post (talents) has 3 custom fields (City, Country, Gender).
  2. Each custom post belongs to the custom taxonomy "Languages" with certain categories such as English, Spanish, Russian etc.

So the query bellow is looking for a female in Canada, Toronto who can speak French.

$querystr= "SELECT * FROM wp_posts
LEFT JOIN wp_postmeta v1 ON (wp_posts.ID = v1.post_id)
LEFT JOIN wp_postmeta v2 ON (wp_posts.ID = v2.post_id)
LEFT JOIN wp_postmeta v3 ON (wp_posts.ID = v3.post_id)
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_id = wp_terms.term_id) 
WHERE
wp_terms.name = 'French' AND wp_term_taxonomy.taxonomy = 'Languages' AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'talents' 
AND v1.meta_value = 'Toronto'
AND v2.meta_value = 'Canada'
AND v3.meta_value = 'female' 
ORDER BY wp_posts.post_date DESC";
Share:
11,000
luiquao
Author by

luiquao

Updated on June 04, 2022

Comments

  • luiquao
    luiquao almost 2 years

    I am trying to search through wp_post & wp_postmeta simultaneously using this query:

    $querystr = "
        SELECT $wpdb->posts.* 
        FROM $wpdb->posts, $wpdb->postmeta
        WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
        AND $wpdb->postmeta.meta_key = 'City' 
        AND $wpdb->postmeta.meta_value = 'Vancouver'
        AND $wpdb->posts.post_status = 'publish' 
        AND $wpdb->posts.post_type = 'talents'
        ORDER BY $wpdb->posts.post_date DESC
     ";
    
    $pageposts = $wpdb->get_results($querystr, OBJECT);
    

    As you can see I search for posts that have City=Vancouver as its meta field. But how do I add one more condition so I won't be getting Vancouver, BC and Vancouver, WA together?

    smth like:

        AND ($wpdb->postmeta.meta_key = 'Country' 
        AND $wpdb->postmeta.meta_value = 'Canada')
        AND ($wpdb->postmeta.meta_key = 'City' 
        AND $wpdb->postmeta.meta_value = 'Vancouver')