Become Wordpress Professional - Your Ultimate Wordpress Guide

Tuesday, 26 March 2013

How to Add WordPress Custom Fields in Posts

What are Wordpress Custom Fields?

WordPress Custom Fields are used to display meta data that contains small bits of information in the posts. Meta data are controlled with keys any values. Keys are the names assign to the custom field and values are the information that appears in the meta-data information

How to Enable WordPress Custom Fields in Wordpress post

By Default, wordpress has disabled the custom fields option. To enable custom fields in wordpress post, Click on "Add New" under the tab "Posts", then click on "Screen Options" on the top right corner of you window.


You will see a drop down with several check boxes. Find "Custom Fields" and then click to check the box.

Once this is done, you will see a new custom fields box under the post text box inside the new post admin area.


How to Display Content using WordPress Custom Fields

Now the custom fields are enabled and we are ready to add content dynamically into posts using WordPress Custom Fields. Let suppose we want to add an Image to wordpress using WordPress Custom Fields.

There are two fields in "Custom Fields" box under post
i) NAME
ii VALUE

First click on "Enter new", write a "NAME (key)" for your custom field and place the link of the image in the "VALUE" box, then click on "Add Custom Fields".

NOTE: name does not matter, you can write what ever name (key) you want, in this tutorial i'm using the name (key) that is "post-image"

How to Call WordPress Custom Fields in Posts

Before we learn how to call custom fields we need to get familiar with the structure of the wordpress function.
get_post_meta //To fetch values from custom fields
$post->ID //To get a post's ID within the $post variable
key // Represents the name of the custom field

Add the following code to your html structure wherever you want to output the metadata info which in this case is the post image.
<?php echo get_post_meta($post->ID, 'key', true); ?>
<?php echo get_post_meta($post->ID, 'post-images', true); ?>// In Our example

Here first argument '$post->ID' is pulling post's ID within the $post variable, the second argument 'key' represents the name of the custom field which must be replaced by the name of your custom field and the third argument is saying if there is a custom field then display else remain empty.

Now I can render the image on the posts for which the image has been set by inserting the following code inside the single.php file of my theme:
 // get_post_meta accepts three parameters ('POST ID', 'CUSTOM FIELD KEY', 'TRUE OR FALSE')


0 comments:

Post a Comment

Please Avoid Spamming. Comments will be moderated before they are published.