0

Trying to fetch all data from wp_postmeta table. I am trying to fetch first meta_key column value. so I am running this query. When I am using print_r then all data showing but when I am using foreach loop then its not working.

<?php
global $wpdb;
$myrows = $wpdb->get_results( "SELECT * FROM wp_postmeta" );
foreach($myrows as $value){
    echo $value->sleeps;
}
  • I suppose you have a post_meta field named sleeps? In that case, the value for that field will be in meta_value, while the meta_key is sleeps. – janh Feb 5 '18 at 7:27
  • janh@ yes Any Idea how to get meta_key value – Sanjay Yadav Feb 5 '18 at 7:33
  • Use $value->meta_value. But in general, you might want to use get_post_meta(), depending on what exactly you are trying to achieve. – janh Feb 5 '18 at 7:43
  • janh@ get_post_meta() only user post id and i need all mete_key value – Sanjay Yadav Feb 5 '18 at 7:44
  • In that case you should be good with using $value->meta_value. Does that work, or is something not going as expected? – janh Feb 5 '18 at 7:56
0

One more for the pot:

$wpdb->get_col can be used to return a "single dimensional" array of all values set for "sleeps"

global $wpdb;
$values = $wpdb->get_col( "SELECT meta_value FROM wp_postmeta WHERE meta_key = 'sleeps'" );

echo implode(',', array_unique($values) );
0

Well friend this query is solve my issue.

global $wpdb;

   $query = $wpdb->get_results("SELECT DISTINCT meta_value 
                              FROM wp_postmeta 
                              WHERE meta_key = 'sleeps'
                              ORDER BY meta_value");
   if (count($query)) {

  foreach ($query as $state) {
    echo $state->meta_value ;
}
   }
0
<?php
global $wpdb;
$myrows = $wpdb->get_results( "SELECT * FROM wp_postmeta" );
foreach($myrows as $row){
    echo $row->meta_key; // meta key
}

Or you can get a post meta keys:

$fields = get_post_custom_keys();
foreach ( $fields as $key => $value ) {
    echo $key;
}

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.