Adding Custom Field to WordPress Post

In WordPress there some default fields in add new post form. These are title, HTML description, category, tags. If we want to add more information to our post, WordPress provides an option to enable custom fields.

These additional information added with the custom fields are called as post meta. This meta data is stored in wp_postmeta table. In wp_postmeta table, each record represents the name and value of a custom field.

In this tutorial, we are going to see how to enable the custom field option in WordPress admin and how to get the custom field value and display them in a template file.

Enabling Custom Field Option in WordPress

In WordPress admin, we can enable Custom Fields checkbox under screen options menu. Figure shows the screen option menu.

adding-custom-field-to-wordpress-post

After enabling this option let us add a custom field named as Website Reference to our post and add value to this field as shown in figure.

custom-field-key-value

custom-field-key-value

Display Custom Meta Data in Post

WordPress provides various functions to access meta data and display them in a page template. The following function will display all meta data of a post in an HTML unordered list.

If you want to read and store this meta data in a variable there is an alternate function get_post_meta() in WordPress. The following code shows the usage of this function.

This function has three parameters. $post_id requires the id of the post, $key requires the custom field name. The third parameter is a Boolean can either be true or false.

If it is true then the function return single custom value or else it returns array of values stored by using the same custom field name.

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *