Wordpress JOIN wp_post和wp_postmeta

时间:2013-03-06 09:11:34

标签: mysql wordpress join

我正在尝试搜索wp_post& wp_postmeta同时使用此查询:

$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);

正如您所看到的,我搜索将City = Vancouver作为其meta字段的帖子。但是,我如何添加一个条件,以便我不会一起到温哥华,不列颠哥伦比亚省和华盛顿州温哥华?

像往常一样:

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

3 个答案:

答案 0 :(得分:2)

根据上面提到的链接,我能够创建此模式,以根据3个meta_values和1个自定义分类法搜索自定义posts_types。

所以我的结构是:

  1. 每个自定义帖子(人才)都有3个自定义字段(城市,国家,性别)。
  2. 每个自定义帖子属于自定义分类“语言”,包含某些类别,如英语,西班牙语,俄语等。
  3. 所以下面的查询正在寻找一位在加拿大,多伦多可以说法语的女性。

    $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";
    

答案 1 :(得分:1)

答案 2 :(得分:0)

我认为以下代码可能会对您有所帮助。如果您有任何疑问,请告诉我。

$args = array(
'post_type' => 'talents',
'posts_per_page' => 10,
'meta_query' => array(
   array(
       'key' => 'City',
       'value' => 'Vancouver',
       'compare' =>  '=',
       'type' => 'CHAR'
        )

),
    'paged' => $paged

);
$temp = $wp_query;
$wp_query = null;


                $wp_query = new WP_Query( $args );
        <?php while (have_posts()) : the_post(); 
            global $post;
/* Your Post content Here                */

endwhile;

wp_reset_query();
/* Pagination Code */
<?php
    global $wp_query;

  $big = 999999999; // need an unlikely integer

echo paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $wp_query->max_num_pages,
    'prev_text'    => __('Previous'),
    'next_text'    => __('Next'),
    'add_fragment' => __($search_page_link)
) );
?>  

您还可以在元值上添加多个条件。    网址: - https://codex.wordpress.org/Class_Reference/WP_Query