Using WordPress ‘get_post_custom()’ PHP function

The get_post_custom() WordPress PHP function retrieves post meta fields based on the post ID.

Usage

To set a variable $custom_fields as a multidimensional array containing all custom fields of the current post:

$custom_fields = get_post_custom();

Parameters

  • $post_id (int, optional) – Post ID. Default is the ID of the global $post.

More information

See WordPress Developer Resources: get_post_custom()

Examples

Retrieve all custom fields of a post

This example retrieves all custom fields of the post with the ID 72:

$custom_fields = get_post_custom(72);
print_r($custom_fields);

Display values of a specific custom field

This example retrieves all custom field values with the key my_custom_field from post ID 72 and displays them:

$custom_fields = get_post_custom(72);
$my_custom_field = $custom_fields['my_custom_field'];
foreach ($my_custom_field as $key => $value) {
    echo $key . " => " . $value . "<br />";
}

Retrieve and unserialize custom field values

This example retrieves a custom field value with the key my_serialized_data from post ID 72, and unserializes it if necessary:

$custom_fields = get_post_custom(72);
$my_serialized_data = $custom_fields['my_serialized_data'][0];
$unserialized_data = maybe_unserialize($my_serialized_data);
print_r($unserialized_data);

Check if a custom field exists for a post

This example checks if a custom field with the key my_custom_field exists for the post with the ID 72:

$custom_fields = get_post_custom(72);
if (isset($custom_fields['my_custom_field'])) {
    echo "Custom field exists!";
} else {
    echo "Custom field does not exist!";
}

Count the number of values for a specific custom field

This example counts the number of values for the custom field with the key my_custom_field for the post with the ID 72:

$custom_fields = get_post_custom(72);
$my_custom_field = $custom_fields['my_custom_field'];
$count = count($my_custom_field);
echo "Number of values for 'my_custom_field': " . $count;