Is there a way to dump a list of all meta keys being used by all posts belonging to a custom post type?
I.e., a post-type named foods, each food (ham, spaghetti, chicken), can have a different meta key, which is generated dynamically.
I can’t know which meta keys have been added, but I’d like to be able to use a list of all of them.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use a simple query to get a distinct list of user-entered meta_keys for a specific post type, then cache the results using the Transients API. The meta keys from this query will be those that do not start with an underscore or number.
function generate_foods_meta_keys(){
global $wpdb;
$post_type = 'foods';
$query = "
SELECT DISTINCT($wpdb->postmeta.meta_key)
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta
ON $wpdb->posts.ID = $wpdb->postmeta.post_id
WHERE $wpdb->posts.post_type = '%s'
AND $wpdb->postmeta.meta_key != ''
AND $wpdb->postmeta.meta_key NOT RegExp '(^[_0-9].+$)'
AND $wpdb->postmeta.meta_key NOT RegExp '(^[0-9]+$)'
";
$meta_keys = $wpdb->get_col($wpdb->prepare($query, $post_type));
set_transient('foods_meta_keys', $meta_keys, 60*60*24); # create 1 Day Expiration
return $meta_keys;
}
To get a list of meta_keys in your template for generating your dropdown, use the following function:
function get_foods_meta_keys(){
$cache = get_transient('foods_meta_keys');
$meta_keys = $cache ? $cache : generate_foods_meta_keys();
return $meta_keys;
}
$meta_keys = get_foods_meta_keys();
Method 2
I believe you’d have to first do a query to gather up all the meta keys for all the custom post type into an array. So something like this:
$args = array(
'post_type' => 'custom-post-type-name',
);
$cpts = new WP_Query($args);
if($cpts->have_posts()) : while($cpts->have_posts() ) : $cpts->the_post();
$meta_values[] = get_post_meta($post->ID);
endwhile; endif;
All your meta values will be stored in an the $meta_values array.
You could do a var_dump($meta_values) to look at the contents of the array to be sure.
Method 3
Use get_post_custom to get all keys and values.
There is also a function called get_post_custom_keys() which you can use to retrieve all of the meta keys.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0