Question

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

Was it helpful?

Solution

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

OTHER TIPS

Get all values of meta_key anywhere:

global $wpdb;
$meta_key = 'picture_upload_1';

$data = $wpdb->get_results($wpdb->prepare( "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key) , ARRAY_N  );

$result = [];
foreach($data as $array){
    $result[] = $array[0];
}

print_r($result);

Would you consider storing the value in the wp_options table instead of the wp_postmetas.

So you could use get_option with your custom key to set and retrieve your value.

https://developer.wordpress.org/reference/functions/get_option/

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top