2013-02-20 58 views
0

我有一個問題,自定義查詢,我寫這樣我不能執行在WordPress

$query = "SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id"; 

查詢時,我直接在我的數據庫運行它,是沒有問題的,它的工作,並選擇自定義行從wp_posts表,但我不能在我的代碼中運行它,並且代碼顯示沒有結果

global $wpdb;  
$query = $wpdb->get_results($query); 
    $query->the_post(); 
    the_title(); 

問題是什麼?

回答

1

我不知道任何關於Wordpress自定義查詢。但正如here提到的那樣,在查詢本身中包含$wpdb->似乎更好。

1

當你使用$ wpdb-> get_results()時,你得到了返回的行數組。你沒有得到實際的WordPress後期對象,所以你不能使用the_post()。 see here for get_results

如果你想查詢帖子,我建議使用query_posts()WP_Query。它看起來是這樣的:

// The Query 
query_posts($args); 

// The Loop 
while (have_posts()) : the_post(); 
    echo '<li>'; 
    the_title(); 
    echo '</li>'; 
endwhile; 
0

變量$query您擁有一組結果。對其執行print_r()查看其值。

另一方面,您使用的是$query->the_post();the_title();,只能在wordpress loop內使用。

解決方案:

#after your query: 
foreach($query as $result){ 
    echo get_the_title($result->ID) . '<br />'; 
}