3

How to get the meta value by meta key

I want to get the value by the meta key. This is what I have tried so far:

   $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_key' => 'picture_upload_1'
);
$dbResult = new WP_Query($args);

var_dump($dbResult);

but I am not receiving the meta value

  • thank you, but as mentioned in the question. i need to get the meta value by the meta key. I do not have the post id! – meWantToLearn Mar 13 '13 at 16:14
  • if you don't have the post ID, how do you know which meta value you're looking for if multiple posts have that key associated with them? what do you plan on doing with the meta values? – Milo Mar 13 '13 at 16:20
  • im writing a plugin, it has a custom post type and shortcode that accepts a parameter. When user saves the custom post, i store the key as slideshow_1 , the 1 will be random unique key, When user uses the shortcode [images id=1] , i will append 1 to slideshow_ and run a query, to get its meta value which has the image path – meWantToLearn Mar 13 '13 at 16:21
  • that doesn't answer either of my questions. – Milo Mar 13 '13 at 16:23
5

WP_Query selects posts and not meta value that is way you are not getting the value. You can use the returned post ID to get the value something like:

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1,
    'meta_key' => 'picture_upload_1'
);
$dbResult = new WP_Query($args);
global $post;
if ($dbResult->have_posts()){
   $dbResult->the_post();
   $value = get_post_meta($post->ID,'picture_upload_1',true);
}

which will get the meta value of the last post published which has a custom field named picture_upload_1

another thing you can do is create a query your self , something like:

 global $wpdb;
 $value = $wpdb->get_var( $wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s LIMIT 1" , $meta_key) );
  • this is super but why do we have to do global $post and $dbResult->the_post(); and why the post_content is empty when we use $dbResult->get_posts(); function – mohsin Oct 20 '17 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.