In WordPress there some default fields in add new post form. These are the title, HTML description, category, tags. If we want to add more information to our post, WordPress provides an option to enable custom fields.
This additional information added with the custom fields are called as post meta. This metadata is stored in the 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. The figure shows the screen options 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 the figure.
WordPress provides various functions to access metadata and display them in a page template. The following function will display all metadata 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> https://phppot.com</li>
//</ul>
?>
If you want to read and store this metadata 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 an array of values stored by using the same custom field name.