我有一个WordPress数据库,我需要使用纯MySQL进行查询,以选择来自名为“guide_category”的自定义分类的所有帖子。我还希望按wp_terms.name
按wp_posts.name
的顺序排序结果。帖子可以位于多个类别中。
因此结果应该类似于:
Category_A
Post A
Post B
Post C
Category_B
Post A
Post B
Post C
Category_C
Post A
Post B
Post C
答案 0 :(得分:7)
global $wpdb;
$query = "
SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON
($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON
($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id = 1
ORDER BY post_date DESC
";
$results = $wpdb->get_results($query);
用您的texonomy id替换term_taxonomy.term_id = 1 它可能适合你
答案 1 :(得分:1)
最终为我工作的是:
SELECT name, post_title
FROM wp_term_taxonomy AS cat_term_taxonomy
INNER JOIN wp_terms AS cat_terms ON cat_term_taxonomy.term_id = cat_terms.term_id
INNER JOIN wp_term_relationships AS cat_term_relationships ON cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id
INNER JOIN wp_posts AS cat_posts ON cat_term_relationships.object_id = cat_posts.ID
INNER JOIN wp_postmeta AS meta ON cat_posts.ID = meta.post_id
WHERE cat_posts.post_status = 'publish'
AND cat_term_taxonomy.taxonomy = 'guide_category'
GROUP BY name, post_title
ORDER BY name, post_title
答案 2 :(得分:0)
在查看/wp-includes/taxonomy.php中的WP_Tax_Query类时,我发现有一个'include_children'选项,默认为true。我用以下内容修改了我原来的get_posts()调用,效果很好:
$pages = get_posts(array(
'post_type' => 'post'
'tax_query' => array(
array(
'taxonomy' => 'taxonomy-name'
)
)
));
更多查询参数列表:http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters