Custom fields let you add extra information to your posts or pages. Displaying this data helps show more details to your visitors.
0
0
Displaying custom field data in Wordpress
Introduction
You want to show a product price on a product page.
You need to display an event date on an event post.
You want to add author bio details that are not in the main content.
You want to show a custom message or note for each post.
Syntax
Wordpress
<?php echo get_post_meta($post->ID, 'custom_field_name', true); ?>get_post_meta fetches the custom field value by its name.
The third parameter true returns a single value instead of an array.
Examples
Displays the 'price' custom field value for the current post.
Wordpress
<?php echo get_post_meta($post->ID, 'price', true); ?>Stores the 'event_date' custom field in a variable and then prints it with a label.
Wordpress
<?php $event_date = get_post_meta($post->ID, 'event_date', true); echo 'Event Date: ' . $event_date; ?>
Checks if a 'note' exists and safely displays it inside a paragraph.
Wordpress
<?php if ($note = get_post_meta($post->ID, 'note', true)) { echo '<p>Note: ' . esc_html($note) . '</p>'; } ?>
Sample Program
This code shows the post title, then checks if a 'subtitle' custom field exists. If yes, it displays the subtitle below the title, then shows the main content.
Wordpress
<?php /* Template part to display a custom field called 'subtitle' */ if (have_posts()) : while (have_posts()) : the_post(); the_title('<h1>', '</h1>'); $subtitle = get_post_meta(get_the_ID(), 'subtitle', true); if ($subtitle) { echo '<h2>' . esc_html($subtitle) . '</h2>'; } the_content(); endwhile; endif; ?>
OutputSuccess
Important Notes
Always use esc_html() or similar functions to safely output custom field data to avoid security issues.
Custom fields are stored per post, so use get_the_ID() or $post->ID to get the current post ID.
If a custom field is empty, check before displaying to avoid showing empty spaces.
Summary
Custom fields add extra info to posts or pages.
Use get_post_meta() to get and display this data.
Always check and sanitize the data before showing it.