Understanding and using Post meta in WordPress

WordPress lets you create by default two types of content – Posts and Pages. For post and pages you can write content in paragraph format in the visual editor in the WordPress admin. This content is shown by your theme on the WordPress front end. But as you start using WordPress for different types of site and start publishing different types of content using WordPress you might find the need to associate more content with the post. This content could be apart from the text and the title you give for the post.

The post meta (also known as custom fields) feature of WordPress helps us to associate more content with a post. This content could be anything depending on the type of site you are making. You can also create any number of post meta which you can associate to a post. So in this article we are going to see how we can add, display and use post meta on our WordPress site.

SEE ALSO: How to Move a WordPress Website from HTTP to HTTPS/SSL

Adding Post meta from the WordPress admin

Adding post meta to a post can be easily done through the WordPress admin .On the post edit page you can add post meta to the post. In case you don’t see the post meta( custom fields metabox) on the post edit page  you can enable to post meta from the screen options as shown below.

Once you have enabled the post meta from the screen options you should be able to see the post meta (custom fields metabox) below the visual editor of the of the post content as shown below.

Are you looking for responsive website templates and online website builder?

Get Startup Design Framework now!

Use coupon code START50 for 50% off!

Here in the drop down list you will see all the post meta keys which you might have added for any other post. You can select the meta key from the drop down list in case you want to add the same post meta even to this post , or you can define a new one by clicking on enter new.

Once you click on enter new you can add the post meta and the value and then click on Add Custom field as shown below.

The post meta will be attached to this post once you will save or publish the post.

Using Post meta in your theme

Once we have added the post meta to the post we might need to display it on the post. WordPress provides us with functions with which we can read the post meta associated with a post. To read the post meta of a post you can use the WordPress function get_post_meta.

The get_post_meta function takes in three arguments the first is the post ID of the post who’s meta you want to read. The second parameter is the meta key you want to read on the post and the third parameter is a boolean in which if you pass true it will return the meta value as a string and if passed false it will return the meta values as an array (this will be useful in case you have multiple values on the same meta key on the same post).

So in case we want to display the Price post meta which we just added on the post you will have to add the following lines to your theme depending on where you want to display the meta. Following code when added in the loop displays the meta

<?php
$price = get_post_meta(get_the_ID(), 'Price', true);
echo 'Cost of the item : '.$price;
?>

Once you have added the above lines and see your loop you should be able to see your post meta as follows.

Adding Post meta via code

There might be some post meta which you want the post writer to update via the WordPress admin. But there might be cases where you might want to programmatically add/update post meta. WordPress provides functions to update the post meta called as update_post_meta

The update_post_meta function takes the first argument as post ID , the second is the meta key , the third is the meta value and the forth is an optional argument which takes the previous value you want to update. update_post_meta calls  add_post_meta in case the key is not already added.

So now we are going to see a small example in which whenever you save a post and the Price meta value is more than $400 we will add a new post meta as discount which will be 15%.

The code to do that is as follows

add_action( 'save_post', 'add_discount_meta' );

function add_discount_meta( $post_id )
{

		$price = get_post_meta($post_id, 'Price', true);
		if(strlen($price) > 0)
		{
			$discount = '0%';
			if(intval(str_replace("$","",$price)) > 400 )
			   $discount = '15%';

			 update_post_meta( $post_id, 'Discount', $discount );
		}

}

In this function we have hooked into the save_post hook which is called whenever a post is saved. In this function we read the Price meta value and check if more than $400. Then accordingly call update_post_meta to update the discount on the post.

So now if we add a post which has Price more than $400 the discount will be added automatically as 15% as shown below.

Some other useful function related to post meta

Following are some other useful functions which you can use related to post meta

get_post_custom_keys – This function takes in the post id and returns an array of all the meta keys associated with that post. You can read more details about it.

get_post_custom_values – This function is used to get all the values for a particular on a post. This is only useful if you have non unique values on a key. You can read more details about it.

get_post_custom – This function takes post ID as input and returns an array of all the meta keys and values on a particular post. You can read more details about it.

delete_post_meta – This function takes in the post ID and the meta key which you want to delete. You can read more details about it.

Post meta on Custom post type

Post meta is a very useful feature. It can be combined with custom post type feature of WordPress. These two features when combined together can be really useful to create a wide variety of sites on WordPress.

To have post meta on custom post type you have to add custom-fields in the supports parameter of the register_post_type function as shown below

register_post_type( 'Mobiles',
        array(
            'labels' => array(
                'name' => __( 'Mobiles' ),
                'singular_name' => __( 'Mobile' )
            ),
        'public' => true,
        'has_archive' => true,
        'supports' => array(
        'title',
        'editor',
        'custom-fields',
        )
        )
    );

To know more about custom post type in WordPress you can read this article.

Conclusion

WordPress has always been a very flexible framework. It has also always been used in sites which are not just plain blogs. With features like post meta WordPress can be customized and used for a wide variety of sites like product display site to a professional portfolio site for example.

WordPress also provides a wide variety of functions around post meta to make the use of post meta in your themes or plugin. These functions are simple to use and hide all the complexity behind them. So have fun while creating post meta in your next WordPress site.

Abbas Suterwala

I am Abbas Suterwala, a software engineer by profession and a passionate coder. I live every moment at the fullest. I love open source projects and mobile development, and I am especially interested in WordPress as blogging platform.

Newsletter

4 Comments
  1. Steve Yancharas Jr. Jan 31, 12:12 am

    It’s refreshing to see the fundamentals of WordPress being used in a real-life scenario. Nice article, short and too the point.

    Reply
    +3
  2. saravanakarthick Aug 26, 12:08 pm

    HI Abbas
    Its very useful for me.please give more post about post meta concept.

    Reply
    0
  3. tara Sep 4, 8:12 pm

    So get_post_meta is used to retrieve the value that is being passed from custom field .What is used to think was when ever i made a post than i can get all the information about the post using this like the category,admin,date of post am I wrong ,Please make me more clear

    Reply
    0

Leave a Reply

*
* Minimum length: 20 characters