The get_post_custom_keys() WordPress PHP function retrieves meta field names for a post.
Usage
$custom_keys = get_post_custom_keys( $post_id );
Parameters
$post_id
(int, optional) – Post ID. Default is the ID of the global$post
.
More information
See WordPress Developer Resources: get_post_custom_keys()
Examples
Retrieve and display custom field keys for a specific post
// Set the post ID $post_id = 42; // Get the custom field keys $custom_keys = get_post_custom_keys($post_id); // Display the custom field keys if ($custom_keys) { foreach ($custom_keys as $key) { if (substr($key, 0, 1) != '_') { echo $key . "<br>"; } } }
Retrieve custom field keys for the current post inside the loop
// Get the custom field keys $custom_keys = get_post_custom_keys(); // Display the custom field keys if ($custom_keys) { foreach ($custom_keys as $key) { if (substr($key, 0, 1) != '_') { echo $key . "<br>"; } } }
Get custom field keys and exclude specific keys
// Get the custom field keys $custom_keys = get_post_custom_keys(); // Exclude specific keys $exclude_keys = array('key_to_exclude', 'another_key_to_exclude'); // Display the custom field keys if ($custom_keys) { foreach ($custom_keys as $key) { if (!in_array($key, $exclude_keys) && substr($key, 0, 1) != '_') { echo $key . "<br>"; } } }
Get custom field keys and their values
// Get the custom field keys $custom_keys = get_post_custom_keys(); // Display the custom field keys and their values if ($custom_keys) { foreach ($custom_keys as $key) { if (substr($key, 0, 1) != '_') { $values = get_post_custom_values($key); echo $key . " => " . implode(', ', $values) . "<br>"; } } }
Count and display the number of custom fields for a post
// Get the custom field keys $custom_keys = get_post_custom_keys(); // Count the custom fields $count = 0; if ($custom_keys) { foreach ($custom_keys as $key) { if (substr($key, 0, 1) != '_') { $count++; } } } // Display the number of custom fields echo "Number of custom fields: " . $count;