2012-03-21 103 views
1

我試圖編寫一個查詢來查找並顯示與我的輸入具有相同自定義字段值的所有帖子。基於wordpress中的自定義字段查詢帖子

在WordPress我有以下...

enter image description here

我查詢...

$pageposts = $wpdb->get_results("SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_value = 'petrol' OR wpostmeta.meta_value = 'local' ORDER BY wpostmeta.meta_value DESC", OBJECT); 

如果我刪除「OR wpostmeta.meta_value = '本地' 這個工作正常並將自定義字段的值作爲「汽油」拉動正確的帖子。

有人可以給我一個關於我會出錯的想法嗎?目前,它的顯示我所有的帖子甚至那些草稿並已刪除,其還循環並展示他們無數次......

回答

1

嘗試:


SELECT wposts.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta 
WHERE wposts.ID = wpostmeta.post_id 
AND (wpostmeta.meta_value = 'petrol' OR wpostmeta.meta_value = 'local') 
ORDER BY wpostmeta.meta_value DESC" 
+0

哇,這實際上是工作!唯一的問題是它通過多次拉動結果,好像它循環一些... – Liam 2012-03-21 10:06:02

+0

你可以添加GROUP BY post_id並查看結果,你的意思是這樣的事情... – 2012-03-21 10:08:20

+0

它仍然拉動刪除的帖子... – Liam 2012-03-21 10:08:28

0

想通了......

<?php 
$customkey = 'Network'; // set to your custom key 
$customvalue = 'Local'; // set to custom value 

global $wpdb; 
$my_posts = $wpdb->get_results("SELECT * FROM $wpdb->posts, $wpdb->postmeta WHERE ID = $wpdb->postmeta.post_id AND meta_key = '$customkey' AND meta_value = '$customvalue' ORDER BY post_date DESC"); 

foreach ($my_posts as $post) : 
setup_postdata($post); 

echo '<div><a href="'; 
the_permalink(); 
echo '"></div>'; 
the_title(); 

endforeach; 
?> 
相關問題