The get_post_custom_values() WordPress PHP function retrieves values for a custom post field.
Usage
get_post_custom_values($key, $post_id);
Parameters
$key(string) – Optional. Meta field key. Default: ”$post_id(int) – Optional. Post ID. Default is the ID of the global$post.
More information
See WordPress Developer Resources: get_post_custom_values()
Examples
Display custom field values for the current post
In this example, we assume the current post has three values associated with the custom field my_key. You can display them like this:
$mykey_values = get_post_custom_values('my_key');
foreach ($mykey_values as $key => $value) {
echo "$key => $value ('my_key')<br />";
}
Output:
0 => First value ('my_key')
1 => Second value ('my_key')
2 => Third value ('my_key')
Retrieve custom field values for a specific post
$post_id = 42; // Replace with desired post ID
$custom_field_key = 'special_key';
$values = get_post_custom_values($custom_field_key, $post_id);
foreach ($values as $value) {
echo "Value: $value<br />";
}
Check if a custom field exists for a post
$post_id = 42; // Replace with desired post ID
$custom_field_key = 'special_key';
$values = get_post_custom_values($custom_field_key, $post_id);
if (!empty($values)) {
echo "Custom field '$custom_field_key' exists for post $post_id.";
} else {
echo "Custom field '$custom_field_key' does not exist for post $post_id.";
}
Display custom field values with labels
$custom_field_key = 'featured_text';
$values = get_post_custom_values($custom_field_key);
if (!empty($values)) {
echo "<h3>Featured Text:</h3>";
foreach ($values as $value) {
echo "<p>$value</p>";
}
}
Retrieve multiple custom fields and their values
$post_id = 42; // Replace with desired post ID
$custom_field_keys = array('field_one', 'field_two', 'field_three');
foreach ($custom_field_keys as $field_key) {
$values = get_post_custom_values($field_key, $post_id);
if (!empty($values)) {
echo "<h4>$field_key</h4>";
foreach ($values as $value) {
echo "<p>$value</p>";
}
}
}