使用Wordpress Meta值进行MySQL查询

时间:2012-03-21 10:47:11

标签: php wordpress

我有一些带有多个元值的wordpress帖子......

enter image description here

我试图编写一个查询,找到所有包含X值的帖子......

$customkey1 = 'Type of Vehicle';
$customvalue1 = $_POST['OPT1']; 

$customkey1 = 'Network'; 
$customvalue1 = $_POST['OPT2']; 

$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' 
    AND meta_key = '$customkey1' 
    AND meta_value = '$customvalue1' 
    AND $wpdb->posts.post_status = 'publish' 
    ORDER BY post_date DESC
");

我认为即时出错我说'WHERE meta_key'等于1件事但是我说如果它等于另一个,我需要看看是否有任何元键是相同的,这是否有意义?

由于

4 个答案:

答案 0 :(得分:3)


SELECT * FROM $wpdb->posts as posts, $wpdb->postmeta as postmeta1 , $wpdb->postmeta as postmeta2 (and more....)
WHERE
posts.ID = postmeta1.post_id
posts.ID = postmeta2.post_id
(and more....)
AND postmeta1.meta_key = '$customkey'
AND postmeta1.meta_value = '$customvalue'
AND postmeta2.meta_key = '$customkey1'
AND postmeta2.meta_value = '$customvalue1'
(and more....)
AND $wpdb->posts.post_status = 'publish'
ORDER BY post_date DESC

答案 1 :(得分:2)

查看get_pages()。它是由wordpress http://codex.wordpress.org/Function_Reference/get_pages

提供的功能
$pages = get_pages(array(
                'meta_key' => $customkey,
                'meta_value' => $customvalue
            ));

但我不确定你是否可以传递多个meta_key

答案 2 :(得分:1)

要获取自定义字段值,请使用

$value1 = get_post_meta($post->ID, 'Type of Vehicle', true);
$value2 = get_post_meta($post->ID, 'Network ', true);

然后,脚本中的任何其他位置都可以回显$ value1和$ value2

你可以添加任意数量的例子

$value1 = get_post_meta($post->ID, 'Custom Field Name 1', true);
$value2 = get_post_meta($post->ID, 'Custom Field Name 2 ', true);
$value3 = get_post_meta($post->ID, 'Custom Field Name 3 ', true);
$value4 = get_post_meta($post->ID, 'Custom Field Name 4 ', true);
$value5 = get_post_meta($post->ID, 'Custom Field Name 5 ', true);

依此类推自定义字段名称,您需要输入自定义字段名称。

答案 3 :(得分:0)

如果两个变量都不同,使用AND时没有意义。你要求它同时是两件事,显然它不可能。它只返回数据(如果存在)并且是$ customkey1和$ customkey的值。但是在你打扰查询它之前,你会用PHP检查它们。

也许你的意思是或者想看看LIKE语句。