简体   繁体   English

根据wordpress中的自定义字段查询帖子

[英]Query posts based on custom field in wordpress

Im trying to write a query that will find and display all of my posts that have the same custom field values as my input. 我正在尝试编写一个查询,该查询将查找并显示与输入具有相同自定义字段值的所有帖子。

In wordpress I have the following... 在WordPress中,我有以下内容...

在此处输入图片说明

My query is... 我的查询是...

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

If I remove 'OR wpostmeta.meta_value = 'local' This works correctly and pulls the correct post with the custom field value as 'petrol' 如果我删除“ OR wpostmeta.meta_value ='local',这将正常工作,并使用自定义字段值将正确的帖子拉为'petrol'

Can anybody give me an idea on where im going wrong? 谁能给我关于我哪里出错的想法? At the moment its display all of my posts even those that are drafts and have been deleted and its also looping and displaying them numerous times... 目前它显示了我所有的帖子,甚至是草稿和已删除的帖子,并且还循环显示了很多遍...

Try: 尝试:


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"

Figured it out... 弄清楚了...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM