How to get meta values of all post of wordpress.

Tuesday, March 22, 2016

Actually, I am posting this because recently I need to get all the meta values of all posts of particular custom post type. 

My need was to create a select box dynamically by the only option field which was filled in custom field. So just copy this to your template or header file. 

<?php function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) {

  global $wpdb;

  if( empty( $key ) )
   return;

 $r = $wpdb->get_col( $wpdb->prepare( "
 SELECT pm.meta_value FROM {$wpdb->postmeta} pm
       LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
       WHERE pm.meta_key = '%s' 
       AND p.post_status = '%s' 
       AND p.post_type = '%s'
   ", $key, $status, $type ) );

   return $r;
}

$meta_value = get_meta_values( 'city', 'coach' ); // city & coach are meta_key & post_type respectively. 
?>
<select name="city">
<option value="">Select City</option> 
<?php foreach ($meta_value as $value) { echo '<option value="'.$value.'">'.$value.'</option>';
}?>

</select>

You Might Also Like

0 comments

Popular Posts

Subscribe