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.
In WordPress admin, we can enable Custom Fields checkbox under screen options menu. Figure shows the screen option menu.
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.
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.
<?php the_meta(); //echo HTML code //<ul class='post-meta'> //<li><span class='post-meta-key'>Website Reference:</span> http://phppot.com</li> //</ul> ?>
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.
<?php $key = "Website Reference"; $post_meta = get_post_meta($post_id, $key, $single); echo '<a href="' . $post_meta . '" target="_blank">' . $post_meta . '</a>'; ?>
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.
This Wordpress code tutorial was published on December 5, 2016.