Liam
Liam

Reputation: 9855

MySQL Query with Wordpress Meta values

I have a few wordpress posts with multiple meta values...

enter image description here

Im trying to write a query that will find all posts with X values...

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

I think where im going wrong is im saying 'WHERE meta_key' equals 1 thing but then im saying if it equals another, I need to see if any of the meta keys are the same, does this make sense?

Thanks

Upvotes: 1

Views: 4860

Answers (4)

Kingkong
Kingkong

Reputation: 56


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

Upvotes: 4

Jeffrey Lang
Jeffrey Lang

Reputation: 192

To get the Custom Field values use

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

Then anywhere else in the script you can echo the the $value1 and $value2

And you can added as many as you want for example

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

And so on where custom field name is you will need to input you Custom field name.

Upvotes: 1

Christophe
Christophe

Reputation: 4828

have a look into get_pages(). it's a function provided by wordpress http://codex.wordpress.org/Function_Reference/get_pages

$pages = get_pages(array(
                'meta_key' => $customkey,
                'meta_value' => $customvalue
            ));

But I'm not sure if you can pass more than one meta_key

Upvotes: 2

deed02392
deed02392

Reputation: 5032

No it does not make sense when you use AND, if both variables will ever be different. You're asking it to be two things at the same time, which obviously it can't be. It would only return data if that existed and was the value of both $customkey1 and $customkey. But you would check those in PHP before you bothered to query it.

Perhaps you meant OR or want to look at LIKE statements.

Upvotes: 0

Related Questions