The get_meta_keys() WordPress PHP function retrieves a list of all previously defined meta keys for a specific post type.
Usage
$all_meta_keys = get_meta_keys();
Parameters
- None
More information
See WordPress Developer Resources: get_meta_keys()
Examples
Display all meta keys for a custom post type
Retrieve all the meta keys for a custom post type called ‘books’, and display them in a list.
// Get all meta keys for the 'books' post type $args = array('post_type' => 'books', 'numberposts' => -1); $books = get_posts($args); $meta_keys = array(); foreach ($books as $book) { $keys = get_post_custom_keys($book->ID); if (!empty($keys)) { foreach ($keys as $key) { if (!in_array($key, $meta_keys)) { $meta_keys[] = $key; } } } } // Display the meta keys in a list echo "<ul>"; foreach ($meta_keys as $key) { echo "<li>" . $key . "</li>"; } echo "</ul>";
Filter posts by meta key
Filter and display posts with a specific meta key called ‘publisher’.
$meta_key = 'publisher'; $args = array( 'meta_key' => $meta_key, 'posts_per_page' => -1 ); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo "<h2>" . get_the_title() . "</h2>"; } } else { echo "No posts found with the meta key 'publisher'."; }
Count posts with a specific meta key
Count the number of posts with the ‘publisher’ meta key.
$meta_key = 'publisher'; $args = array( 'meta_key' => $meta_key, 'posts_per_page' => -1 ); $query = new WP_Query($args); echo "Number of posts with the 'publisher' meta key: " . $query->post_count;
Display unique values of a specific meta key
Retrieve and display the unique values of the ‘publisher’ meta key.
$meta_key = 'publisher'; $unique_values = array(); $args = array( 'meta_key' => $meta_key, 'posts_per_page' => -1 ); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $value = get_post_meta(get_the_ID(), $meta_key, true); if (!in_array($value, $unique_values)) { $unique_values[] = $value; } } echo "Unique values for the 'publisher' meta key:<br>"; echo implode(', ', $unique_values); } else { echo "No posts found with the meta key 'publisher'."; }