2016-07-14 143 views
-6

我有一個WordPress數據庫,需要使用純MySQL進行查詢才能從名爲'guide_category'的自定義分類中選擇所有帖子。我也想按照wp_terms.name的順序排列結果,並在wp_posts.name的順序內排列結果。帖子可以駐留在多個類別中。如何查詢自定義WordPress類別中的所有帖子

所以結果應該看起來像:

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

你能發表表格的結構嗎? – Philipp

+2

***爲什麼*** SQL而不是本機Wordpress –

+2

有很多理由使用SQL而不是wordpress。也許這是一個不同的技術,正在尋找使用WordPress的數據,也許它是爲了遷移的目的,YADDA YADDA。 –

回答

0

工作,這是最終爲我工作:

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 
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

+0

我正在尋找一個純粹的MySQL答案...不是PHP/WordPress。 – bigmike7801

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

更換term_taxonomy.term_id = 1與texonomy ID 可能它會爲你

相關問題