Domains.co.za
  • Domains
    Register Domains
    Register your perfect domain today.
    It’s quick and easy.
    AI Domain Name Generator AI Domain Name Generator
    Create your perfect Domain Name today.
    Transfer Domains
    Transfer your domains to us in a few easy steps.
    Whois Search
    View the whois information on a domain name.
    Bulk Domain Registrations
    Register and check the availability of multiple domains at once.
    Bulk Domain Transfer
    Move multiple domains to us quickly and easily.
    Domain Protection
    Protect your personal information.
  • Hosting
    cPanel Hosting Web Hosting
    cPanel Web Hosting From R109/mo
    WordPress Hosting
    Experience the best in WordPress Hosting
    Email Only Hosting
    Easy setup, automated updates & backups
    Site Builder Site Builder
    Create your stunning website, it's fast and easy
  • VPS
    Linux VPS Hosting
    UltraFast  VPS Hosting From R209/mo
    Windows VPS Hosting
    UltraFast  VPS Hosting From R1139/mo
    Managed cPanel Hosting Managed cPanel Hosting
    Managed cPanel Virtual Machines From R2999/mo
    Self-Hosted n8n VPS Self-Hosted n8n VPS
    Unlimited Workflow Automation From R319/mo
  • Security
    Domain Validated SSL
    Domain Validated SSL Certificates
    Organization Validated SSL
    Organization Validated SSL Certificates
  • Resellers
    Domain Reseller
    Resell Domains on our platform From R89 per domain
    Web Hosting Reseller
    Reseller Web Hosting on SSD Hosting Servers From R419/mo
  • Help
    Open a Ticket
    Log a support or billing enquiry with one of our departments.
    011 640 9700
    Need Help? Give us a call
    About Us
    Information about Domains.co.za
    Knowledgebase
    Check out our extensive Knowledge Base for help
    Network Status
    Just to check everything is hunky dory
    Accreditations
    View the organisations and registries we are accredited with
    Blog
    View insights into the latest scoops
    Articles & Tutorials Articles & Tutorials
    Practical guides and insights to help you succeed
  • Checkout
011 640 9700
Contact Support
Sign In
Domains.co.za - Link In Bio
Header Text: Show Any Custom Field on Your WordPress Site, Safely
25Sep
9

The WordPress get_post_meta Function Helps You Turn Custom Fields Into Dynamic Content

Summarize with:
ChatGPT
Claude
Perplexity

A WordPress post provides a title, body text, and a featured image. Most real projects need more. For example, a listing needs a price, an event needs a date and a venue, and a review needs a rating. Custom fields fill that gap. They store extra data against a post, and the WordPress get_post_meta function pulls it back out so you can show it on the page.

This guide explains the entire setup. You learn how get_post_meta works, when to use it, and how to display custom field data without opening a security hole. You receive the syntax, code you can copy directly into a project, and find the correct way to escape every value. We also cover custom post types, WooCommerce, ACF, performance, and the small errors that trip people up.

You don’t need to be an expert to follow along. If you can read a little PHP and access your dashboard or files, you’ll be fine.

KEY TAKEAWAYS

  • The WordPress get_post_meta function retrieves a post’s custom field values from the database when you provide a post ID and a field key.
  • Set $single to true for a single value as a string, or false for an array of every value stored under that key.
  • Escape every value before you print it, using esc_html for text, esc_url for links, and esc_attr for attributes.
  • Inside the Loop, get_the_ID() hands you the current post’s ID, so you don’t have to write it by hand.
  • It also works on pages and custom post types, but reach for WooCommerce and ACF functions when you’re pulling data from them.

TABLE OF CONTENTS

  • KEY TAKEAWAYS
  • What Are Post Metadata & Custom Fields?
  • What get_post_meta Does & Why It Matters
  • Common Use Cases
  • WordPress get_post_meta Function Syntax
  • Use get_post_meta Inside WordPress Loop
  • Display Custom Fields in WordPress Safely
  • Practical WordPress get_post_meta Function Examples
  • How to Add get_post_meta to Your Site
    • Edit a Template in a Child Theme
    • Use a WPCode Plugin
    • Build a Site-Specific Plugin
  • get_post_meta with Custom Post Types, WooCommerce, & ACF
  • Keep WordPress get_post_meta Function Fast
  • Security When Displaying Post Meta
  • Common Mistakes & How to Fix Them
  • South African Use Cases
  • Hosting, Environment, & POPIA
  • When to Consult a Developer
  • Final Thoughts
  • Power Up Your Site: How to Install a WordPress Plugin
  • FAQS
  • Other Blogs of Interest

What Are Post Metadata & Custom Fields?

WordPress post metadata is extra information attached to a piece of content, whether it’s a post, a page, a product, an event, or a custom post type. WordPress saves it as key-value pairs. The key is a label (reading_hours_spent) and the value is what you stored.

Those pairs are what most people call WordPress custom fields. Each one belongs to a single content item and sits in a database table called wp_postmeta.

A post can hold many fields, and one field can even store more than one value. Custom fields are built into WordPress, so no plugin is required, though plugins can make them easier to manage. Once a value is saved, you need a way to fetch and print it. That’s what get_post_meta is for.

What get_post_meta Does & Why It Matters

The WordPress get_post_meta function reads metadata for one post from the database. Give it a post ID and a field key, and it returns the stored value. Nothing appears until you echo that value yourself, so you decide exactly where and how it shows.

That’s what makes it useful. Instead of hardcoding a price or a date into a page, you read it from a field.

One template can then show different details for every item. A single service-page layout can drive hundreds of services, each with its own data. Editors update the fields, the front end updates itself, and you write the logic only once. This is the backbone of flexible WordPress development.

Common Use Cases

You’ll use get_post_meta any time a page needs a value from outside the main content. Common cases include:

  • Reading time and editorial notes.
  • Product specs, prices, and stock labels.
  • Event dates and venues.
  • Branch details.
  • Downloadable resources.
  • Ratings and badges.
  • Custom callouts.
  • SEO or schema values.

Custom post type fields fit the same pattern. If the information suits a clear label and value, a custom field is a tidy home for it.

WordPress get_post_meta Function Syntax

The function takes three parameters:

get_post_meta( $post_id, $key, $single );
ParameterData TypeDefault ValueRequired
$post_idIntegerNoneYes
$keyStringEmpty stringNo
$singleBooleanFalseNo

$post_id is the only required parameter. It tells WordPress which item to read from. In a template that already shows a post, get_the_ID() returns the current ID.

$key is the exact field name, and it’s case-sensitive, so reading_hours_spent and Reading_Hours_Spent count as two different fields. Leave the key out, and you’ll get every field on the post, which you seldom want.

$single sets the shape of the result. When set to true, it returns a single string; when false (the default), it returns an array of all values under that key. For a field with a single value, true saves you from unpacking an array before printing.

Use get_post_meta Inside WordPress Loop

Most template code runs inside the WordPress Loop, the block WordPress uses to process the current post. While you’re in the Loop, get_the_ID() returns the ID of the post on screen, so you don’t have to type it by hand.

$reading_time = get_post_meta( get_the_ID(), 'reading_time', true );
if ( ! empty( $reading_time ) ) {
    echo esc_html( $reading_time ) . ' min read';
}

That fetches the value, checks it isn’t empty, and prints it safely. Outside the Loop, get_the_ID() relies on the global $post object; if that isn’t set (or points to the incorrect post), get_the_ID() will return false, causing get_post_meta() to fail. In those contexts, pass the specific post ID directly (e.g., $post->ID or a known integer).”

Returning One Value or an Array

The $single parameter trips up a lot of people. With true, you get a string. With false, you get an array, even when only one value exists.

// Single string
$rating = get_post_meta( get_the_ID(), 'rating', true );

// Array of every value under this key
$gallery = get_post_meta( get_the_ID(), 'gallery_image', false );

Echo an array directly, and PHP prints the word Array. So, loop through the array when a field holds several values and uses true when it holds one. Match $single to the field, and your output stays clean.

Display Custom Fields in WordPress Safely

Reading a value is only half the job. Before you print anything from the database, escape it. Escaping turns risky characters into a safe form, which stops broken markup and blocks common attacks. Do it for every value, even ones you entered yourself, and choose the function that matches where the value lands.

Use esc_html() for plain text that sits between HTML tags: a note, a label, a short description.

$note = get_post_meta( get_the_ID(), 'author_note', true );
echo esc_html( $note );

Use esc_url() for any URL, including image sources and download links.

$pdf = get_post_meta( get_the_ID(), 'resource_pdf', true );
echo '<a href="' . esc_url( $pdf ) . '">Download the guide</a>';

Use esc_attr() for values that go inside an HTML attribute, such as a title, a class, a data attribute.

$label = get_post_meta( get_the_ID(), 'badge_label', true );
echo '<span class="badge" title="' . esc_attr( $label ) . '">Featured</span>';

The right function matters. A URL run through esc_html can still break, and attribute text without esc_attr can allow markup to slip in.

Practical WordPress get_post_meta Function Examples

A few patterns cover most day-to-day work. First, check a field exists before you show it, so empty pages don’t print stray labels.

$price = get_post_meta( get_the_ID(), 'product_price', true );
if ( ! empty( $price ) ) {
    echo 'From R' . esc_html( $price );
} else {
    echo 'Price on request';
}

Next, loop through a field that holds several values, say a list of venues:


$venues = get_post_meta( get_the_ID(), 'event_venue', false );
if ( ! empty( $venues ) ) {
    foreach ( $venues as $venue ) {
        echo '<li>' . esc_html( $venue ) . '</li>';
    }
}

And while you’re debugging, read every field at once by omitting the key. This returns an associative array where each value is itself an array, so pull only what you need in production.

$all_fields = get_post_meta( get_the_ID() );

How to Add get_post_meta to Your Site

There are three ways to add this code. You can edit a template in a child theme, drop the code into a snippet plugin, or build a small site-specific plugin. Each suits a different situation, and each should be tested before it reaches live visitors.

Edit a Template in a Child Theme

Editing a template gives you the most control over placement, so it’s correct when the value is part of the design, such as a price beneath a product title.

However, before continuing with this method, ensure you back up your site first, then work on a staging copy if you can. And use a child theme. Otherwise, an update will wipe your changes.

Once you’re ready, go through the following steps:

  1. Go to Appearance → Theme File Editor, or use File Manager and browse to wp-content/themes/your-child-theme-folder.
  2. Open the template that controls the page. For a single post, that’s usually single.php.
  3. Add your escaped get_post_meta code where you want the value to show.
  4. Click Update File to save changes, then reload the page and check.

Ensure your code is enclosed within PHP tags.

EXAMPLE:
<?php
$value = get_post_meta(get_the_ID(), 'custom_field_key', true);
if ($value) {
    echo '<p>' . $value . '</p>';
}
?>
The WordPress get_post_meta Function Helps You Turn Custom Fields into Dynamic Content - Edit Template in a WordPress Child Theme Files

Use a WPCode Plugin

The WPCode plugin is a safer home for small bits of PHP, since your code survives theme changes and stays in a single place. It suits values that aren’t tied to the design.

Here’s how to use it:

1. Install and activate the WPCode plugin. For step-by-step instructions, see How to Install a WordPress Plugin.

2. Go to Code Snippets → +Add Snippet. Click +Add Custom Snippet.

The WordPress get_post_meta Function Helps You Turn Custom Fields into Dynamic Content - Add Custom Code Snippet Using WPCode Plugin

3. Name your snippet to easily identify it.

4. Choose code type, which is PHP Snippet in this case.

5. Paste your code.

6. Scope it so it only runs where you need it:

  • Insertion Method: Choose whether you wish to run it automatically or only when a shortcode is provided.
  • Location: Select where you wish to run it: Everywhere, frontend only, admin only, etc.
  • Schedule Snippet: Select the start and end dates to run this snippet within a specific timeframe.

7. Save and activate this snippet.

Scoping is the part people skip. The snippet below adds a reading time above single posts only, using a hook and a few conditions so it never fires where it shouldn’t:

add_filter( 'the_content', 'show_reading_time' );
function show_reading_time( $content ) {
    if ( is_singular( 'post' ) && in_the_loop() && is_main_query() ) {
        $reading_time = get_post_meta( get_the_ID(), 'reading_time', true );
        if ( ! empty( $reading_time ) ) {
            $note    = '<p class="reading-time">' . esc_html( $reading_time ) . ' min read</p>';
            $content = $note . $content;
        }
    }
    return $content;
}
The WordPress get_post_meta Function Helps You Turn Custom Fields into Dynamic Content - Add a PHP Code Snippet Using WPCode Plugin

Build a Site-Specific Plugin

For features that aren’t about design, a small plugin beats theme code. Your logic stays in place when you switch themes, and you can turn it off with a click. get_post_meta is one of the WordPress PHP functions that fits this pattern well.

  1. Login to your hosting control panel.
  2. Go to the public_html/wp-content/plugins directory.
  3. Create a new folder and name it with a lowercase, hyphen-separated name (e.g., my-new-custom-plugin).
  4. Inside this new folder, create a new .php file (e.g., my-new-custom-plugin.php).
  5. Add a custom header with your required code:
<?php
/**
 * Plugin Name: WordPress Website Custom Meta Output
 * Description: This plugin displays selected custom fields on the front end.
 * Version: 1.0.0
 */
// Your get_post_meta code goes here.
  1. Save the file and activate it from the Plugins menu in the WordPress dashboard.

get_post_meta with Custom Post Types, WooCommerce, & ACF

The WordPress get_post_meta function isn’t only for blog posts. It works anywhere WordPress uses a post ID, which is nearly everywhere. Custom post types are the clearest case. Services, locations, case studies, events, and resources all read their fields the same way a post does. They are built on the same IDs, so nothing changes.

WooCommerce is where you should ease off the raw meta. Products are custom post types and rely heavily on metadata. But WooCommerce’s own functions handle formatting and follow the store’s logic. Newer versions also store some order data differently from plain post meta.

// Preferred
$product = wc_get_product( get_the_ID() );
$price   = $product->get_price();

// Works, but skips WooCommerce logic
$price = get_post_meta( get_the_ID(), '_price', true );

If you’re adding product data to pages, using WooCommerce shortcodes is easier than using raw code. Advanced Custom Fields (ACF) also keeps most values in post meta, but its get_field() usually returns cleaner output. It hands you a formatted value that matches the field type, while raw meta might return an image ID or serialised data you then unpack.

// ACF handles the formatting
$link = get_field( 'brochure_link' );

// Raw meta may return an ID or serialised data
$link = get_post_meta( get_the_ID(), 'brochure_link', true );

So, use the get_post_meta function for plain fields, and reach for the plugin’s function when the field type is involved.

Keep WordPress get_post_meta Function Fast

get_post_meta is light on its own. When WordPress loads a post, it caches that post’s metadata in memory. Calling the function a few times for the same post usually won’t hit the database again. You don’t need to collect values in variables to save queries.

The real cost is messy templates, not the function. Don’t pull every field with an empty key when you need one. Keep your template logic simple. Watch the heavy extras instead: big images, long loops, calls to outside services. Those slow a page far more than a meta lookup ever will. That speed counts double for the many South African visitors browsing on mobile and patchy connections.

Security When Displaying Post Meta

Custom fields often end up in front of the public, so a little care pays off. Escaping every value in the output is the first and biggest step, and it’s worth saying twice because it’s easy to forget in a busy template.

Beyond that, validate values where it makes sense, for example, by confirming that a value really is a number. Don’t display private or internal fields meant only for the admin area.

Treat anything a visitor submitted with extra suspicion. And add capability checks in admin-facing code, so only authorised users can see or change sensitive fields. Most of this is just deciding what belongs in public before you print it.

Common Mistakes & How to Fix Them

A few common mistakes cause most issues with get_post_meta():

  • Wrong field key, or the wrong capitalisation.
  • Wrong post ID, or no post ID at all.
  • Code running outside the Loop, where get_the_ID() returns nothing.
  • Forgetting $single and echoing an array by mistake.
  • Printing values without escaping.
  • Editing the parent theme instead of a child theme.
  • Assuming ACF output is plain text when it may be an array.
  • Pulling every field when you need one.
  • Showing private fields to the public.
  • Running a snippet sitewide with no conditions.

When a field won’t show, work through this in order:

  1. Confirm the field exists on the post you’re testing.
  2. Check the exact key name, capitalisation included.
  3. Inspect the value with var_dump(), but only in development. Never leave it on a live page.
  4. Turn on Debug Mode to surface PHP errors.
  5. Read your error logs. Here’s how to configure WordPress error logs.
  6. Confirm which template file the page uses.
  7. Clear your cache, since an old page can hide the fix.
  8. Test with a post ID you know has the field filled in.
  9. Check whether a plugin stores the value differently.
// Development only. Remove before going live.
var_dump( get_post_meta( get_the_ID(), 'reading_time', true ) );

Most problems come down to a wrong key, a missing ID, or code in the wrong place.

South African Use Cases

WordPress get_post_meta function earns its keep in everyday local work:

  • Agencies build a single service-page template and allow custom fields to populate each client’s details.
  • Developers create branch pages that pull an address, opening hours, and a map link from fields.
  • Online stores add product metadata for specs, warranties, and stock.
  • Event sites show dates and venues straight from fields, which helps when a schedule shifts.
  • Training providers list course length, price, and the next intake.
  • Professional firms show team credentials and registration numbers, and publishers add reading time and editorial notes.

Since so many visitors arrive on mobile, keeping these fields light is part of good WordPress development, not an extra.

Hosting, Environment, & POPIA

Solid code needs a solid place to run. Aim for reliable hosting, a staging area, regular backups, a current PHP version, and access to your files and error logs.

For heavier or client sites, VPS hosting for WordPress developers provides more room and control, plus SFTP or SSH for quick fixes. Load-shedding adds a local twist, so make and test template changes during stable power windows. Keep recent backups off-site and rely on staging so that a half-finished edit never reaches a live page.

The WordPress get_post_meta Function Helps You Turn Custom Fields into Dynamic Content - VPS Hosting in South Africa

Privacy also deserves a mention. Post meta can quietly hold personal or business information, especially in custom client workflows. Under POPIA, that data needs the same care as anything else you store.

Keep private fields out of public output, and don’t print internal notes by accident. The same goes for off-the-page data: exported databases, backups, and logs can all contain field data, so store and share them responsibly. This is practical housekeeping, not legal advice.

When to Consult a Developer

You can handle plenty of this yourself, but some jobs are worth a second pair of hands. Call for assistance when the site breaks after you add PHP, or when metadata sits in complex arrays you can’t unpick.

The same goes for ACF, another field plugin, WooCommerce data, or custom post type templates. Schema that depends on meta values, work that really needs a custom plugin, and debug logs full of PHP errors all qualify. If you’d rather not go it alone, Domains.co.za support can point you the right way.

Final Thoughts

get_post_meta is a small function with an outsized role. It turns static custom fields into dynamic content and allows a single template to serve many pages without hardcoding a thing.

Paired with escaped output, backups, and a real testing routine, it’s one of the safest and most useful tools you’ve got. Choose one field, display it safely, and build from there.

Build and customise WordPress websites with more confidence on reliable WordPress hosting in South Africa from Domains.co.za. You’ll have secure infrastructure, practical local support, and developer-friendly hosting options behind you.

Strip Banner Text - WordPress Hosting built for South Africa, with staging, automatic updates, and local support. [Learn More]

Power Up Your Site: How to Install a WordPress Plugin

VIDEO: Power Up Your Site: How to Install a WordPress Plugin

FAQS

What’s the difference between get_post_meta() and get_post_custom()?

get_post_custom() pulls every custom field on a post at once, and it always returns arrays of values. get_post_meta() lets you target a single key, which keeps your display code cleaner.

How do I add or update a custom field value in code?

Use update_post_meta( $post_id, $key, $value ) to set a value. If the field doesn’t exist yet, it creates one, and if it does, it updates it. Use add_post_meta() when you wish to store more than one value under the same key. These are the write-side partners to get_post_meta().

Does get_post_meta() work with users, categories, or comments?

Not directly, but WordPress provides a matching function for each. Use get_user_meta() for users, get_term_meta() for categories and tags, and get_comment_meta() for comments. They all follow the same pattern, with an ID, a key, and a single flag.

Why do some meta keys start with an underscore?

A leading underscore marks the field as protected. WordPress then hides it from the Custom Fields panel in the editor, so it’s meant for values your code uses, not for hand editing. WooCommerce’s _price is one you’ll meet often. You can still read it with the get_post_meta WordPress function.

Can I use get_post_meta() with block or full site editing themes?

Yes, though the method changes. Block themes build pages from HTML templates rather than PHP files, so you can’t drop your code into single.php the way you would in a classic theme. Instead, you can show a field through a dynamic block, the newer block bindings feature, or a plugin that prints the value. In classic PHP templates, get_post_meta() still works as shown above.

Other Blogs of Interest

  • Should You Disable WordPress Comments Or Manage Them More Effectively?
  • WordPress Debug Mode Turns Hidden Website Errors Into Useful Diagnostic Evidence
  • WordPress Version Control Helps Teams Build, Test, & Recover With Less Risk
  • Your WordPress Header Does More Than Sit At The Top Of The Page
  • Deleting Unused WordPress Themes Keeps Your Website Cleaner, Safer, And Easier To Manage
Author - Rhett Freeman
Rhett Freeman

Rhett isn’t just a writer at Domains.co.za – he’s our resident WordPress content guru. With over 8 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 and articles 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 Hosting  WordPress - get_post_meta Function
Views 57

Categories

  • Home
  • General
  • Website Design
  • WordPress Hosting

Domains.co.za - Link In Bio

Domains.co.za - Web Hosting

Domains.co.za - Site Builder Add-on

Domains.co.za - WordPress Hosting

Domains.co.za - AI Domain Name Generator

Domains.co.za

We are a domain name and website hosting provider committed to offering affordable web hosting solutions that enable businesses to establish a strong online presence.

Secure Payment Gateways

Peach Logo DPO Logo PayFast Logo Visa Logo Mastercard Logo Netcash Logo Ozow Logo

Read more about our secure payments.

Hosting

  • WordPress Hosting
  • Web Hosting
  • Managed cPanel Hosting
  • Email Hosting
  • Linux VPS Hosting
  • Windows VPS Hosting
  • Site Builder
  • PHP Extended Support
  • Self-Hosted n8n VPS

Domains

  • Register Domains
  • Transfer Domains
  • WHOIS Search
  • Bulk Domain Registrations
  • Bulk Domain Transfers
  • Domain Protection

Security

  • Domain Validated SSLs
  • Organization Validated SSLs

Resellers

  • Reseller Web Hosting
  • Domain Reseller
  • Registrar Services
  • Integration
  • Domain Reseller Login

Legal

  • Terms and Conditions
  • UDRP
  • Our SLA
  • Abuse Policy
  • Disclosure Requests

Our Company

  • About Us
  • Contact Us
  • Accreditations
  • Careers

Help

  • System Status
  • Affiliate Program
  • Knowledgebase
  • Blog
  • Report Abuse
Facebook Instagram YouTube Twitter LinkedIn Google Business
Copyright © 2026 Domains.co.za. All Rights Reserved.