Hosted.com
  • Domains New!
    Domain Registration Register Domains

    Quick and easy domain name registration

    AI Domain Name Generator AI Domain Name Generator New!

    Create the perfect domain using our AI generator

    Domain Transfer Transfer Domains

    Hassle-free transfer of domains to us

    Whois Lookup Whois Lookup

    Check domain name registrant information

    Bulk Domian Registrations Bulk Domain Registrations

    Find and register multiple domain names in one go

    Bulk Domain Transfers Bulk Domain Transfers

    Transfer multiple domains to us at once

  • Hosting
    cPanel Web Hosting cPanel Web Hosting

    cPanel Web Hosting with an easy control panel

    Email Hosting Email Hosting

    Hosting for professional domain-based emails

    Website Builder Website Builder

    Drag & drop widgets and professionally designed templates

  • WordPress Hosting
  • SSL Certificates
  • Help
    Open a Ticket Open a Ticket

    Stuck? Send us your query for help

    About Hosted.com About Us

    Find out more about Hosted.com

    Hosted.com Knowledgbase Knowledgebase

    Plenty of helpful information to assist you

    Hosted.com Network Status Network Status

    Check out our Network status anytime

    Hosted.com - Approved Providers Approved Providers

    Some of the accredited suppliers we use

    Hosted.com Blog Blog

    Insights and tips to boost your business

    Hosted.com Articles Articles

    Informative articles to help you succeed

  • Checkout
  • Contact Support Contact Support
    Sign In Sign In
Contact Support Contact Support
Sign In Sign In
  • Domains New!
  • Domain Registration Register Domains

    Quick and easy domain name registration

    AI Domain Name Generator AI Domain Name Generator New!

    Create the perfect domain using our AI generator

    Domain Transfer Transfer Domains

    Hassle-free transfer of domains to us

    Whois Lookup Whois Lookup

    Check domain name registrant information

    Bulk Domian Registrations Bulk Domain Registrations

    Find and register multiple domain names in one go

    Bulk Domain Transfers Bulk Domain Transfers

    Transfer multiple domains to us at once

  • Hosting
  • cPanel Web Hosting cPanel Web Hosting

    cPanel Web Hosting with an easy control panel

    Email Hosting Email Hosting

    Hosting for professional domain-based emails

    Website Builder Website Builder

    Drag & drop widgets and professionally designed templates

  • WordPress Hosting
  • SSL Certificates
  • Help
  • Open a Ticket Open a Ticket

    Stuck? Send us your query for help

    About Hosted.com About Us

    Find out more about Hosted.com

    Hosted.com Knowledgbase Knowledgebase

    Plenty of helpful information to assist you

    Hosted.com Network Status Network Status

    Check out our Network status anytime

    Hosted.com - Approved Providers Approved Providers

    Some of the accredited suppliers we use

    Hosted.com Blog Blog

    Insights and tips to boost your business

    Hosted.com Articles Articles

    Informative articles to help you succeed

  • Checkout

WordPress get_post_meta Function: How to Display Custom Fields

Main \ Tutorials \ Website Development \ WordPress Coding \ WordPress Troubleshooting \ WordPress get_post_meta Function: How to Display Custom Fields

  Posted November 5, 2024  |   Updated February 20, 2025  |    Rhett Freeman

Header Text - How to Display Custom Fields in WordPress title=Hosted.com Tutorial - WordPress get_post_meta Function: How to Display Custom Fields

Custom fields in WordPress are extra information you can add to your posts. Consider them special notes or details that help you customize your content.

For example, if you’re running a blog, you might want to show the author’s bio, the reading-time, or other specific information that doesn’t come with WordPress by default. This is where Metadata comes in. Metadata is the data about your content that’s stored in custom fields.

Now, here’s where the get_post_meta function plays a huge role. You can add this function to your site’s code to grab Metadata and display it on your website. This function shows custom fields on your posts or pages without much coding.

Here we show you what the get_post_meta function is, why it’s important, and how to use it. We’ll also explore some examples to see various uses of WordPress to get post meta functions. By the end, you’ll know exactly how to retrieve custom data and display it on your WordPress site, whether you do it manually or with the help of plugins.

KEY TAKEAWAYS

  1. The get_post_meta function retrieves extra information (Metadata) from WordPress posts.
  2. The function uses parameters like $post_id, $key, and $single to find specific custom field data.
  3. You can manually add the function to templates or use plugins like WPCode to display Metadata.
  4. The function can dynamically show custom fields like text, images, or post status.
  5. This function offers flexibility without much coding, making it easy to manage custom fields.
  6. If you need to update post meta dynamically, it can be combined with other functions to enhance content customization.

TABLE OF CONTENTS

  • KEY TAKEAWAYS
  • What is WordPress get_post_meta Function?
  • get_post_meta Function Parameters
    • $post_id
    • $key
    • $single
  • How to use the get_post_meta Function to Display Custom Fields
    • Add get_post_meta Manually to Post Template
    • Add get_post_meta Using a Plugin
  • Examples of Using get_post_meta
    • Check if Custom Field Exists
    • Retrieve & Display Images via Metadata
    • Access Published Post Objects & Meta Keys
  • FAQS
  • Other Related Tutorials & Blogs:

What is WordPress get_post_meta Function?

The get_post_meta function in WordPress retrieves Metadata from a specific post and displays it on the front end, which you see as a website visitor. As we mentioned, Metadata is the additional information related to your post, such as custom fields you add to enhance the content.

This function fetches this meta information, like a tag or value, stored in the WordPress database. For example, if you have a custom field for “author bio”, the get_post_meta function will pull that information from the database and display it on the post where you need it.

get_post_meta Function Parameters

The get_post_meta function syntax has 3 main parameters:

get_post_meta($post_id, $key, $single)

Each parameter plays a different role in helping WordPress retrieve the correct Metadata for a given post. Let’s break them down one by one below:

$post_id

First, the $post_id parameter tells WordPress which post you want to get the Metadata from. It’s the unique ID assigned to every post in WordPress. For example, if you wish to display meta details for post #25, you would use $post_id = 25 in the function.

This is important because WordPress needs to know which post you’re referring to. To retrieve all post IDs, use the get_the_ID() function. If the $post_id is missing or incorrect, WordPress won’t know where to pull the data from, and you might get an empty result or an error.

In exceptional cases, when you’re in a WordPress loop (which processes posts automatically), you can skip specifying $post_id because WordPress already knows which post you’re working with.

$key

Next, we have the $key parameter. The $key is the name of the meta field (a.k.a custom field) you want to retrieve. Meta fields in WordPress are identified by specific names, like “reading-time” or “rating”.

If you’ve added a custom field to a post with the name “reading-time”, you need to set $key = ‘reading-time’ in your function call to get the value of that field. If unsure of the exact name or if the $key doesn’t exist, WordPress cannot give any information.

However, if you leave the $key empty (which means you set it as $key=”), WordPress will return all meta fields for that post. This can be helpful if you’re unsure of the meta field names or want to check everything is available.

$single

Finally, the $single parameter controls whether WordPress should return a value or multiple ones. When you set $single = true, WordPress will return only the first value it finds for the meta field. This is useful if you only need one piece of data, like a price.

But, if you want to get all values for a field that stores multiple entries (like multiple authors or tags), set $single = false. In that case, WordPress will return an array (a list of values) instead of just one.

A common issue arises if you accidentally set $single to true when multiple values are expected; you’ll only get the first value, and the rest will be ignored.

Here’s the table representing the parameter name, data type, default value, and whether it’s a required or optional parameter:

Parameter NameData TypeDefault ValueRequired/Optional
$post_idintNoneRequired
$keystring” (empty string)Optional
$singleboolfalseOptional

By understanding and using $post_id, $key, and $single, you may pull exactly the type of Metafield data you need in WordPress and avoid errors that could cause your custom fields to display incorrectly. Here’s an example of how to use all three parameters:

// Get the price meta field for post #25
$price = get_post_meta(25, 'price', true);
echo $price;  // Outputs the price value

This simple code retrieves the value for the price meta field for post number 25 and prints it on the page.

Remember, the WordPress get post meta function not only helps you grab the Metadata; it can also be used for other purposes, such as checking if a post has any meta fields or finding out how many meta fields exist for a given post. Let’s look at a few examples to understand its different uses:

//check if a post has any meta fields
<?php
$all_meta = get_post_meta(get_the_ID(), '', false);
if (!empty($all_meta)) {
    echo '<p>This post has meta fields.</p>';
} else {
    echo '<p>No meta fields found for this post.</p>';
}
?>

Here’s another example:

//count the number of meta fields for a given post
<?php
$all_meta = get_post_meta(get_the_ID(), '', false);
$meta_count = count($all_meta);
echo '<p>This post has ' . $meta_count . ' meta fields.</p>';
?>

How to use the get_post_meta Function to Display Custom Fields

In this section, we’ll learn 2 ways to use the get_post_meta function to show meta fields on your WordPress site. As these approaches provide the same results, you can pick either one, based on your comfort and preference. Let’s start by manually adding the function to your post template.

Add get_post_meta Manually to Post Template

To display meta fields, invoke the get_post_meta function inside your WordPress theme’s post template. The file you will edit is usually called single.php; it controls how individual posts look on your site. However, if you want to display custom fields on a page, you may edit the WordPress template file (page.php).

Before making any changes to your theme files, you should create a backup of your website theme. This way, if something goes wrong, you can easily restore it. Remember, you’ll lose your custom changes whenever the theme gets updated. Therefore, we recommend creating a child theme to avoid unexpected errors and to ensure the modifications persist after a theme update.

Once you’re ready, you should access the single.php file. Do so using your WordPress dashboard and the Hosted.com File Manager feature. For this tutorial, we use the WordPress dashboard first:

Go to Appearance → Theme File Editor from your WordPress admin dashboard.

WordPress get_post_meta Function - Access Theme File Editor

On the right side, you’ll see a list of theme files. Look for a single.php file under the Theme Files menu and click on it to open. This file controls the layout for single posts. Add your custom field code here.

WordPress get_post_meta Function - Edit single.php File

Inside the single.php file, you need to add the get_post_meta function where you want the custom field to show. Just ensure the function is wrapped with the open (<?php) and closed (?>) php tags.

Here’s an example:

<?php
$value = get_post_meta(get_the_ID(), 'custom_field_key', true);
if ($value) {
    echo '<p>' . $value . '</p>';
}
?>

This code will display the value of the custom field. If you want to show multiple custom fields, you can loop through them. Here’s how to do that:

<?php
$all_meta = get_post_meta(get_the_ID(), '', false);
foreach ($all_meta as $key => $values) {
    foreach ($values as $value) {
        echo $key . ': ' . $value . '<br>';
    }
}
?>

This code will list all custom fields for the given post, showing the key (field name) and its value. Once you’ve added the code, save the file and visit your site’s front end to see the custom fields displayed on your posts.

Sometimes users don’t find the Theme File Editor in their WordPress admin area, which means the theme you’re using doesn’t allow you to modify the page template file. This is where the Hosted.com File Manager comes in to locate the required file.

Uncover various customization options available for optimizing your WordPress site.
For exceptional performance and reliable support, choose Hosted.com’s WordPress Hosting.

Here’s how Hosted.com’s WordPress Hosting users can access this feature:

First, log in to your Hosted account. Then, navigate to Manage Services → WordPress Hosting and click Manage.

WordPress get_post_meta Function - Manage Domain Settings

After that, click Login under the Product Information section.

WordPress get_post_meta Function - Access Hosted’s cPanel

Next, click File Manager, which you find under Files.

WordPress get_post_meta Function - Access File Manager

Now, you need to find the single.php file inside the active theme folder in the public_html/wp-content/themes directory. To make changes, right-click on the file and choose Edit.

WordPress get_post_meta Function - Edit single.php via File Manager

Another option is to place the function in your theme’s functions.php file and call it from your post template. This approach is useful if you work with custom post types and want to maintain a cleaner main template file.

Add get_post_meta Using a Plugin

This method is useful if you’re not comfortable editing theme files directly. Here, you use the WPCode plugin to add custom code and display meta fields safely in WordPress. This is a simple, straightforward method.

However, you can only use this method is you already installed the WPCode plugin. If you haven’t already done so, install and activate it. After that, go through the following steps:

Go to WordPress Dashboard → Code Snippets > Add Snippet.

WordPress get_post_meta Function - Select Add Snippet Option

Then, switch to the Snippet Library tab. In the list of available options, hover over the Add Your Custom Code (New Snippet) and click +Add Custom Snippet.

WordPress get_post_meta Function - Add Custom Snippet

Next, choose the code type of your snippet, which, in our example, is the PHP Snippet.

WordPress get_post_meta Function - Select Code Snippet Type

Give your snippet a title like “Display Reading-Time”. In the code editor, paste the following code to display the reading-time for the given post:

echo get_post_meta( get_the_ID(), 'reading-time', true );
WordPress get_post_meta Function - Add Code Snippet

Ensure you replace reading-time with your actual custom field key.

After that, scroll down to the Insertion settings and choose Insert Method. In this example, we select Auto Insert because we want the snippet executed automatically.

Next, find the location, which, in this example is Run Everywhere. This tells the plugin to run your code on all single post pages. You can also choose more specific settings if you only want the custom field to appear on certain post types.

WordPress get_post_meta Function - Run Code Everywhere

Once you’ve entered your code and set the insertion options, click Save Snippet then Activate. Your custom field will now be displayed on all single posts.

WordPress get_post_meta Function - Save and Activate Snippet

Now, visit one of your single posts to see if the custom field is showing. If not showing, refresh the page or clear your browser cache.

Examples of Using get_post_meta

The get_post_meta function can be used in various ways to display information dynamically on your WordPress site. Here are some examples:

Check if Custom Field Exists

You can use get_post_meta() to check whether a specific custom field exists before displaying it. In the code, the function checks if the reading-time custom field is present. If it exists, it displays the reading-time; otherwise, it will show a fallback message.

$reading_time = get_post_meta(get_the_ID(), 'reading-time', true);
if (!empty($reading_time)) {
    echo '<p>Reading-time: ' . esc_html($reading_time) . '</p>';
} else {
    echo '<p>No reading-time available.</p>';
}

Retrieve & Display Images via Metadata

If you store image URLs in custom fields, you can display them like this:

$image_url = get_post_meta( get_the_ID(), 'featured-image', true );
echo '<img src="' . $image_url . '" alt="Featured Image">';

Access Published Post Objects & Meta Keys

You can fetch published post objects and other Metadata with the following code:

$args = array(

    'post_type'      => 'post',    // Change 'post' to your custom post type if needed

    'post_status'    => 'publish', // Only fetch published posts

    'posts_per_page' => -1         // Retrieve all published posts

);

// Fetch posts based on query

$posts = get_posts( $args );

// Loop through each post and display its meta keys

if ( ! empty( $posts ) ) {

    foreach ( $posts as $post ) {

        // Output the post title

        echo '<h2>' . get_the_title( $post->ID ) . '</h2>';

        // Get all meta keys and values for the current post

        $meta_keys = get_post_meta( $post->ID );

        // Check if there are any meta keys and display them

        if ( ! empty( $meta_keys ) ) {

            echo '<ul>';

            foreach ( $meta_keys as $key => $value ) {

                echo '<li>' . esc_html( $key ) . ': ' . esc_html( $value[0] ) . '</li>';

            }

            echo '</ul>';

        } else {

            echo '<p>No custom fields for this post.</p>';

        }

    }

} else {

    echo '<p>No published posts found.</p>';

}
?>

These examples show how versatile the get_post_meta function is when displaying custom fields on your WordPress site.

Strip Banner Text - Reliable WordPress Hosting with tailored customization options. [Learn more] title=Reliable WordPress Hosting With Tailored Customization Option

FAQS

What does get_post_meta do?

This function retrieves custom field data (Metadata) from a WordPress post or page.

What is a custom field in WordPress?

Custom fields store extra information you add to posts, like price, ratings, or any unique detail.

Is get_post_meta safe to use?

Yes, but sanitize the output to prevent security risks.

Does get_post_meta work with custom post types?

Yes, the function works with any post type, including custom ones.

What happens if a custom field doesn’t exist?

The function returns an empty string, or ‘false’ if no data is found for the specified key.

Other Related Tutorials & Blogs:

– WooCommerce Shortcodes: A Guide to Their Uses & Benefits

– WordPress DDOS Protection: Shield Your Website From Online Threats

– WordPress SQL Injection: 5 Tips to Secure Your Site

– Fix an Error Establishing A Database Connection in WordPress

– Automated WordPress Security Scans – 5 Reasons Why You Need Them

  • About the Author
  • Latest Posts
Rhett Freeman( Researcher, Content Writer and WordPress Content Guru )

Rhett isn’t just a writer at Hosted.com – he’s our resident WordPress content guru. With over 6 years of experience as a content writer, with a background in copywriting, journalism, research, and SEO, and a passion for websites.

Rhett authors informative blogs, articles, and Knowledgebase guides that simplify the complexities of WordPress, website builders, domains, and cPanel hosting. Rhett’s clear explanations and practical tips provide valuable resources for anyone wanting to own and build a website. Just don’t ask him about coding before he’s had coffee.

  • WordPress Cron Jobs: How To Setup, View & Manage
  • How To Remove Powered By WordPress From A Website
  • How To Undo Changes In WordPress: Pages, Posts & Revisions
  Tutorials, Website Development, WordPress Coding, WordPress Troubleshooting  WordPress get_post_meta Function

Categories

  • 35 Browser Errors
  • 3 Domains
  • 3 Ecommerce
  • 1 General
  • 6 Hosting
  • 16 Managed WordPress Hosting
  • 10 Scaling WordPress Hosting
  • 3 SEO
  • 5 SSL Certificates
  • 152 Tutorials
  • 12 Web Hosting
  • 107 Website Development
  • 196 WordPress
  • 26 WordPress Basics
  • 86 WordPress Coding
  • 17 WordPress Ecommerce Hosting
  • 16 WordPress Hosting & SEO
  • 13 WordPress Hosting Beginners
  • 12 WordPress Hosting Costs
  • 18 WordPress Hosting Performance
  • 18 WordPress Hosting Types
  • 18 WordPress Migration
  • 20 WordPress Security
  • 48 WordPress Troubleshooting

Recent Posts

  • WordPress Cron Jobs: How To Setup, View & Manage
  • How To Remove Powered By WordPress From A Website
  • How To Undo Changes In WordPress: Pages, Posts & Revisions
  • How To Hide Page Title In WordPress: 5 Easy Ways
  • WordPress iFrames: How To Use And Embed Pages, Videos And More

What Our Customers say..

Hosted.com

We make hosting simple

Hosted.com is a Web Hosting and Domain name provider with a soft spot for start-ups and small businesses. We believe you are the star of the show, and our products and plans underpin this belief.

Stripe

Read more about our Secure Payment methods here.

Hosting

  • cPanel Web Hosting
  • WordPress Hosting
  • Website Builder
  • Email Hosting

Company

  • Contact Us
  • About Us

Domains

  • Register Domains
  • Transfer Domains
  • Bulk Register
  • Bulk Transfer
  • Whois Lookup

Security

  • SSL

Resources

  • Support
  • Knowledgebase
  • Blog
  • Articles
  • Payment Methods
  • Affiliates
  • Sitemap

Legal

  • Universal Terms & Conditions
  • Domain Expiration Policy
  • Abuse Policy
  • Privacy Policy
  • Billing Policy
Find us on Instagram
Find us on Facebook
Find us on LinkedIn
Find us on Pinterest
Find us on X / Twitter
Find us on YouTube
Google My Business
Copyright © 2025 Hosted.com. All Rights Reserved. T.1749975267.8072
        {
    "auth": 0.3852272033691406,
    "total": 1749975267.807227
}