Wordpress JOIN wp_post 和 wp_postmeta
Posted
技术标签:
【中文标题】Wordpress JOIN wp_post 和 wp_postmeta【英文标题】:Wordpress JOIN wp_post and wp_postmeta 【发布时间】:2013-02-20 23:51:29 【问题描述】:我正在尝试使用此查询同时搜索 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 作为元字段的帖子。但是如何再添加一个条件,这样我就不会将温哥华,不列颠哥伦比亚省和温哥华,WA 放在一起?
类似的东西:
AND ($wpdb->postmeta.meta_key = 'Country'
AND $wpdb->postmeta.meta_value = 'Canada')
AND ($wpdb->postmeta.meta_key = 'City'
AND $wpdb->postmeta.meta_value = 'Vancouver')
【问题讨论】:
【参考方案1】:基于上面提到的链接,我能够创建这个模式来搜索基于 3 个元值和 1 个自定义分类的自定义 posts_types。
所以我的结构是:
-
每个自定义帖子(人才)都有 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";
【讨论】:
【参考方案2】:我认为下面的代码可能会对您有所帮助。如果您有任何疑问,请告诉我。
$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
【讨论】:
以上是关于Wordpress JOIN wp_post 和 wp_postmeta的主要内容,如果未能解决你的问题,请参考以下文章