How to Use get_post_meta in WordPress: Syntax and Examples
Use
get_post_meta($post_id, $key, $single) to get custom field values from a WordPress post. Provide the post ID, the meta key name, and set $single to true to get a single value or false for an array of values.Syntax
The get_post_meta function retrieves metadata (custom fields) for a post in WordPress.
- $post_id: The ID of the post you want to get metadata from.
- $key: The meta key name as a string. Use an empty string to get all meta data.
- $single: Boolean. If true, returns a single value. If false, returns an array of values.
php
get_post_meta( int $post_id, string $key = '', bool $single = false )
Example
This example shows how to get a single custom field value called 'subtitle' from a post with ID 42 and display it.
php
<?php $post_id = 42; $subtitle = get_post_meta($post_id, 'subtitle', true); if ($subtitle) { echo 'Subtitle: ' . esc_html($subtitle); } else { echo 'No subtitle found.'; } ?>
Output
Subtitle: Your custom subtitle here
Common Pitfalls
Common mistakes include:
- Using
$singleas false when expecting a single value, which returns an array instead. - Not sanitizing output before displaying, which can cause security issues.
- Using the wrong post ID or meta key, resulting in empty or unexpected results.
php
<?php // Wrong: expecting a string but $single is false, returns array $meta_wrong = get_post_meta(42, 'subtitle', false); echo implode(', ', $meta_wrong); // Outputs array values as string // Right: set $single to true to get a string $meta_right = get_post_meta(42, 'subtitle', true); echo esc_html($meta_right);
Output
Your custom subtitle here
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| $post_id | ID of the post to get meta from | 42 |
| $key | Meta key name (custom field name) | 'subtitle' |
| $single | Return single value (true) or array (false) | true |
Key Takeaways
Use get_post_meta with the post ID, meta key, and single flag to retrieve custom fields.
Set the third parameter to true to get a single value instead of an array.
Always sanitize output before displaying to avoid security risks.
Check that the post ID and meta key are correct to get expected results.