What Is the WordPress get_post_meta Function and How to Use It to Display Custom Fields
A custom field in a WordPress website stores a post’s metadata in the back end. To retrieve and display this data on the front end, add the get_post_meta function to your site’s code.
WordPress developers show such information to help visitors navigate the website and understand its content more easily. For example, you can feature the product price, additional category tag, and custom header in your post.
In this tutorial, we will explain the WordPress get_post_meta function and its parameters. You will also learn two common methods to add it to your website – using WordPress Theme Editor or a plugin.
What Is the WordPress get_post_meta Function?
The WordPress get_post_meta function lets you retrieve values from post meta fields and display them on the front end, showing additional information on your content. Add this function to your WordPress theme’s configuration file or use a plugin like WPCode.
WordPress get_post_meta Function Parameters
The WordPress get_post_meta function syntax has three parameters and looks as follows:
get_post_meta( $post_id, $key, $single );
Here’s what each parameter means:
- $post_id – the post from which the metadata is obtained. To retrieve all post IDs, use get_the_id(). If you use a non-existing post ID, the function will return an empty string.
- $key – the custom field’s meta key to retrieve the data from. Leaving it empty will retrieve data from all post meta fields in the given post. If the custom field doesn’t exist or lacks a meta value, it returns an empty array.
- $single – a parameter determining whether the function returns an array of values or a single one. The default value is TRUE, which obtains a single array. Setting it as FALSE retrieves an array of multiple values from the specified meta key.
Important! If the $single parameter is TRUE and the post meta field contains multiple data values, the function retrieves only the first value. Meanwhile, using an empty string will return all metadata for the same key in the current post.
You can also use the function for other purposes, such as checking whether a specific meta field exists in the given post ID:
$custom_field = get_post_meta( get_the_id() ); if (!empty($custom_field)){ echo "Meta field exists in this post" } else { echo "This post doesn’t contain a custom field" }
How to Use the get_post_meta Function to Display Custom Fields
In this section, we will explain two methods to use the WordPress get_post_meta function. Since both have the same outcome, feel free to pick the one that looks more comfortable.
How to Add the get_post_meta Function to a Post Template Manually
The first method to add the function is by editing your WordPress page template file. We recommend creating a child theme to avoid errors and ensure the changes persist after an update.
You can edit the page template file via the admin dashboard or Hostinger’s File Manager. Here’s how to do so using the first method:
- Log in to your WordPress admin dashboard. From the sidebar, navigate to Appearance → Theme File Editor.
- Under the Theme Files menu, locate the single.php file.
- Add the following snippet at the end of the file before the <?php closing tag. Remember to change the values according to your needs:
echo get_post_meta(Post ID, 'key', true );
- After the function, add the WordPress loop to allow the code to pull and display the retrieved data. Here’s an example that displays the post meta value at the bottom of your post:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php endwhile; else: ?> <?php endif; ?>
- Click Update File to save the changes.
A WordPress loop is optional if you retrieve a single value from one meta key. However, it is required when the function returns data from multiple custom fields or an array of values. Here’s how you loop an array:
foreach ($your_function_variable as $value){ //command goes here }
Important! Due to WordPress caching, this function is case-sensitive.
If the Theme File Editor menu is missing, it means your theme doesn’t let users modify the page template file. Luckily, Hostinger’s Managed WordPress hosting users can use the hPanel’s File manager to locate it.
The single.php file is in the currently active theme folder within public_html/wp-content/themes. To edit the file, right-click on it and select Edit.
Alternatively, add the function to your theme’s functions.php file and call it in your post template. This method is more suitable if you have custom post types and want to keep the main template file’s code clean.
How to Add the get_post_meta Function Using a Plugin
If you can’t access the single.php file, add the function using a plugin. We will show you how to do it using the WPCode plugin’s free version.
After downloading and installing the plugin, follow these steps:
- From the admin dashboard, navigate to Code Snippets → Add Snippet.
- Hover over the Add Your Custom Code and click Use Snippet.
- From the Code Type drop-down menu, select PHP Snippet.
- Enter your code into the Code Preview field. It should include the function and loop.
- Scroll down to the Insertion section and change the settings based on your needs. For example, we will select Auto Insert and Insert After Content as the location.
- Click Save Snippet in the top right corner.
- Press the activation toggle to apply the code.
WordPress get_post_meta Function Examples
This section will explain several get_post_meta usage examples for your inspiration.
Accessing Published Post Objects and Meta Keys
$published_posts = get_posts(array('post_status' => 'publish')); foreach ($published_posts as $post) { $post_id = $post->ID; $meta_keys = get_post_meta($post_id);}
The code example uses get_posts to fetch each published post object and iterate it through the function using the foreach loop to access its meta keys.
Fetching the HTML img Element Representing an Image Attachment
$attachment_id = get_post_meta($post_id,'_thumbnail_id', true); if ($attachment_id) { $image_html = wp_get_attachment_image($attachment_id, 'large'); echo $image_html; } else { echo 'No images!'; }
This code retrieves the image’s attachment ID from a custom field in a post and passes the obtained value to the wp_get_attachment_image function. Using the ID, it gets the image’s img element.
You can also use the code to retrieve a post thumbnail by changing the wp_get_attachment_image function’s $size parameter.
Access Dynamic Data Related to a Post Meta Field
$dynamic_suffix = 'example'; $custom_field_name = 'custom_field_' . $dynamic_suffix; $dynamic_data = get_post_meta(get_the_id(), $custom_field_name, true); if ($dynamic_data) { echo 'Dynamic Data: ' . esc_html($dynamic_data); } else { echo 'No dynamic data found.'; }
You can introduce dynamically generated fields using a dynamic suffix. For example, we create custom_field_example using the example suffix in the code.
This code retrieves and displays data from the dynamic custom field in the current post. If the value is present, the function labels the data as dynamic. Otherwise, it outputs an error message if the value doesn’t exist.
Fetches the Post Status Based on Metadata
$post_status = get_post_meta(post_ID, 'custom_field_post_status', true); if ($post_status) { echo 'Custom Status: ' . esc_html($post_status); } else { echo 'Custom status not found or unavailable.'; }
The code fetches post statuses from their custom fields. If the status exists, it displays the value. Otherwise, the function returns an error message.
Conclusion
The WordPress get_post_meta function lets you retrieve the post metadata from a custom field and display it to website visitors. It has three parameters – the post ID, the field’s meta key, and a determiner that sets whether to obtain a single value or multiple ones.
To use this function, add the code to your theme’s single.php or functions.php file. You can do so using your hosting control panel’s file manager or via the WordPress admin dashboard’s Theme File Editor under the Appearance menu.
Alternatively, use a plugin like WPCode. After downloading and installing it, add your code as a new PHP snippet and configure the insertion settings, including where to display the metadata in your post. To enable it, click the activation toggle.
Should you have any more questions, feel free to explore our WordPress tutorial.
WordPress get_post_meta FAQ
In this section, we will answer common questions about the WordPress get_post_meta function.
How Do I Use the get_post_meta Function?
Add the function in your theme’s single.php file or functions.php if you have a custom post type. In the code, specify the post’s ID, the meta field from which you want to retrieve the data, and whether to retrieve only one value or an array of them. If you have multiple custom fields and arrays, loop the values to display them.
How Does WordPress the get_post_meta Function Work With Custom Fields?
The WordPress custom fields let users assign additional metadata to a post, which will be stored in the database. The get_post_meta function lets you retrieve current post data from a meta field and display the information on your front end.
Can I Use the get_post_meta Function to Display All Custom Fields?
Yes. The function’s second parameter specifies the custom meta field to retrieve the data from. If you use an empty string, the function will retrieve post meta values from all custom fields. Meanwhile, setting it as FALSE returns the entire post meta array.
How Do I Find the Post ID for the get_post_meta Function?
There are various methods to retrieve the WordPress post ID. The easiest one is to use a plugin like Reveal IDs, which adds a new ID column in the All Posts and All Pages menus. Alternatively, use the echo get_post_id function to print the ID in your post.