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.
3 s
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();