Using WordPress ‘post_custom()’ PHP function

The post_custom() WordPress PHP function retrieves post custom meta data fields.

Usage

post_custom( $key );

Custom example:

echo post_custom('my_custom_field');

Parameters

  • $key (string) (Optional) Meta data key name. Default: ”

More information

See WordPress Developer Resources: post_custom()

Examples

Display a custom field

Retrieve and display the value of a custom field called ‘author_bio’:

echo post_custom('author_bio');

Check if a custom field exists

Check if a custom field called ‘featured_image’ exists for the current post:

if (post_custom('featured_image')) {
// Custom field exists, perform an action
}

Retrieve a custom field and assign to a variable

Retrieve the value of a custom field called ‘price’ and assign it to a variable:

$price = post_custom('price');

Display a custom field with a fallback

Retrieve and display the value of a custom field called ‘rating’, or show ‘N/A’ if the field does not exist:

echo post_custom('rating') ? post_custom('rating') : 'N/A';

Retrieve and format a custom date field

Retrieve a custom date field called ‘event_date’, format it, and display the result:

$event_date = post_custom('event_date');
$formatted_date = date('F j, Y', strtotime($event_date));
echo $formatted_date;