Nicola Mustone

Happiness Lead @ Automattic



Custom Fields and How to Use get_post_meta

custom red tuned ford mustang at night

Did you know about custom fields in WordPress? Most probably you already use them and you don’t know that they are called as such.

Some time ago, I wrote an article about how to add fields to products in WooCommerce. Those fields are custom product fields, and their values are post meta.

If you check the article and its comments, you will notice that many people were confused about how to get their value, so let me explain to you what they are and how to get them!

What Are Custom Fields?

These powerful tools, often unrecognized by many, are also known as metadata or post meta. Custom fields function as descriptive data for your posts, enriching them with necessary details. Whether it’s specifying the post type or formatting in WooCommerce, like pricing or product types, custom fields add invaluable layers of information. They’re primarily stored in the wp_postmeta database table, with some exceptions like post type.

Efficiently Retrieve Custom Field Values with get_post_meta

WordPress offers the versatile get_post_meta function, adaptable for any post type – be it a post, page, or product. This function demands three parameters:

  • $post_id: The specific ID of the post.
  • $key: The custom field’s name, often prefixed with _ to indicate hidden post meta.
  • $single (optional): Determines if the custom field value is singular or an array.

Here is a usage example:

<?php
// Get the value of the post meta with name `_my_post_meta_name`
$post_meta_value = get_post_meta( $post->ID, '_my_post_meta_name', true );
// Print the post meta value
printf( 'The value of my post meta is %s', $post_meta_value );
view raw functions.php hosted with ❤ by GitHub

Simplifying Custom Fields Management: Adding and Updating

Adding custom field values to the database is straightforward with the add_post_meta function. This function requires four parameters: $post_id (the post ID), $key (custom field name), $value (field value), and $single (optional, to avoid duplicate keys). For updating existing custom fields, the update_post_meta function works similarly.

Streamlining Deletion of Custom Field Values

As you might guess, the function to delete custom fields values is delete_post_meta(). It needs three parameters: $post_id (the post’s ID), $key (the custom field name), and $value (optional, the specific value to delete).

Enhancing Your WordPress Experience

To conclude, post meta in WordPress, play a vital role in enriching your content with detailed, specific information. Mastery of functions like get_post_meta, add_post_meta, and delete_post_meta empowers you to manage these fields effectively. This understanding is essential for anyone looking to fully leverage WordPress capabilities, ensuring a more robust and finely tuned website. As you continue to work with these tools, remember that they are not just features, but pathways to a more dynamic and customized WordPress experience.

Advertisements

Subscribe to This Blog

Receive new articles from this blog directly in your inbox! No spam guaranteed!

Join 651 other subscribers

Contribute to Improving This Blog

Did you enjoy this article? Was it helpful? Contribute to help me write more articles! The funds collected from this blog are reinvested directly into improving my skills or the blog so that I can provide more and better content!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

€5.00
€15.00
€100.00
€5.00
€15.00
€100.00
€5.00
€15.00
€100.00

Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly
Advertisements

More Posts That You Might Like…


6 responses to “Custom Fields and How to Use get_post_meta”

  1. Hi Nicola,

    Great article, and very informative to my limited knowledge of custom fields. I’d appreciate some advice on a certain custom field.
    On my single WooCommerce product page is an inquiry form with the usual contact information fields. There are also two more fields I’ve added: SKU & PRODUCT. The SKU field is working fine and pulling in the associated SKU: [post_meta key=”_sku”]
    However, the product field is not pulling in anything: [post_meta key=”_product”] Is there another word I need to replace ‘product’ or is there an entirely different string of text to apply?
    Thanks, Gareth

  2. When I had tons of meta keys to work with to display some custom content for custom post types, instead of making several dozen calls to the get_post_meta function to grab the keys I wanted, I wrote this function instead. Basically it gets all of the meta keys and filters out all of the arrays with single values while maintaining any arrays that actually do have multiple values and returns an associative array of the results. If you have lots of single values to get, it saves you from having to iterate over every result to get your $k=>$v pairs so you can just access them by $mk[‘my_custom_meta_key’].
    function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
    }

    function filter_gpm($array){
    $mk = array();
    foreach($array as $k => $v){
    if(is_array($v) && count($v) == 1){
    $mk = array_push_assoc($mk, $k, $v[0]);
    } else {
    $mk = array_push_assoc($mk, $k, $v);
    }
    }
    return $mk;
    }
    Call it like so
    $mk = filter_gpm( get_post_meta( get_the_ID() ) );

  3. Thanks for this little nice tutorial

    1. You’re welcome! I’m happy you enjoy it.

  4. Shubhra Vashishtha Avatar
    Shubhra Vashishtha

    thank you so much for the code, it helps me a lot

    1. You’re welcome!

Leave a Reply

Advertisements

Categories

Newsletter

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Join 651 other subscribers

About The Author

Hi, I’m Nico! Support Lead at Automattic, championing WordPress.com & WooCommerce. Off-duty, I’m at Elemental Beacon, leading epic D&D adventures. Let’s connect, whether it’s about WordPress or a quest!

Advertisements

Don't Miss a Thing!

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Join 651 other subscribers

Continue Reading

%d bloggers like this: