Power of Custom Fields in WordPress
- May 12, 2017
- Leave a comment
Custom Fields are a type of metadata which allows you to store extra data with each WordPress post/page. There are multiple names of custom fields like metadata, post meta, etc. While adding a new post/page in WordPress, you’ll see draggable boxes which are being used to store information about your post/page:
In other words, custom fields are the most powerful tool that can be used for customizing the template files. A custom field is handled with key/value pairs. The meta-data element is named as the “key” while the “value” is the information that will appear in the meta-data list on every single post (with which the information is being associated).
To fetch and display the custom fields value on a particular post/page, use get_post_meta() function as follows:
$variable = get_post_meta($post_id, $key, $single);
Here, $post_id is the ID of the post you want the meta values for.
Now, use either $post->ID to get a post’s ID within the $post variable scope or use get_the_ID() to retrieve the ID of the current item in the WordPress Loop.
$key is a string containing the name of the meta value you want. $single can either be true or false. If set to true then the function will return a single result, as a string. If false or not set, then the function will return an array of the custom fields.