MySQL Query with WordPress Meta values

I have a few wordpress posts with multiple meta values…

enter image description here

Read More

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

Related posts

Leave a Reply

4 comments


  1. 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
  2. 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.

  3. 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.