How to Display Custom Field in Theme in WordPress
To display a custom field in a WordPress theme, use the
get_post_meta() function inside your theme template files. This function retrieves the value of a custom field by its key for the current post or page.Syntax
The get_post_meta() function is used to get the value of a custom field. It requires three parameters:
$post_id: The ID of the post or page.$key: The name of the custom field.$single: Boolean to return a single value (true) or an array (false).
Example syntax:
php
get_post_meta($post_id, 'custom_field_key', true);
Example
This example shows how to display a custom field called subtitle inside the WordPress loop in a theme template file:
php
<?php if (have_posts()) : while (have_posts()) : the_post(); $subtitle = get_post_meta(get_the_ID(), 'subtitle', true); if ($subtitle) { echo '<h2 class="subtitle">' . esc_html($subtitle) . '</h2>'; } the_content(); endwhile; endif; ?>
Output
<h2 class="subtitle">Your custom subtitle text here</h2>
<p>The post content will appear below the subtitle.</p>
Common Pitfalls
Common mistakes when displaying custom fields include:
- Not using
get_the_ID()or the correct post ID, causing no data to show. - Forgetting to set the third parameter
$singletotruewhen expecting a single value. - Not escaping output with
esc_html()or similar functions, risking security issues. - Trying to display custom fields outside the loop without specifying the post ID.
php
<?php // Wrong: missing post ID $subtitle = get_post_meta('subtitle', true); // Incorrect // Right: include post ID and single true $subtitle = get_post_meta(get_the_ID(), 'subtitle', true); // Correct ?>
Quick Reference
| Function | Purpose | Example |
|---|---|---|
| get_post_meta | Get custom field value | get_post_meta(get_the_ID(), 'key', true) |
| the_ID | Get current post ID | get_the_ID() |
| esc_html | Escape output for safety | echo esc_html($value) |
Key Takeaways
Use get_post_meta() with the correct post ID and key to retrieve custom fields.
Always set the third parameter to true to get a single value when needed.
Escape output with esc_html() to keep your site secure.
Use get_the_ID() inside the loop to get the current post's ID.
Custom fields must be added in the WordPress admin or via code before displaying.