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.
2 thoughts on “Power of Custom Fields in WordPress”
Thanks but I am not good in php, I have added a custom field with name of “Location”
How can I use above code with my custom filed name “Location” ?
Here is the link to WordPress guide to using custom fields https://developer.wordpress.org/reference/functions/get_post_meta/
Make sure your $key will be Name of your custom field currently which is Location.
Thank you for writing to us. Let us know if you still need further assistance.