How to use WordPress Custom Fields

by Hough on March 24, 2011

Custom Field is one of the best feature of WordPress which allows user to enter Meta-data or arbitrary extra information related to the post or page. For example let’s say you have site of particular product and you want to insert some extra information related to product like size,height,price etc. You can insert these extra information into custom fields.

WordPress Custom Fields

You can find custom field panel just below the Post & Page edit Administration Panels. Although in new version of wordpress 3.1 it remain hidden by default if not used before. You can make it visible from “Screen Option” which is at the top of you Administration screen. Just click the checkbox of custom fields and you’ll get it.

Meta data in custom field is handled with Key and Value pair. As you can see in above image, there are two things Name and Value. In name you can enter name of, meta data and in Value field you can enter value of it. Just insert name and value and your custom field is added.

WordPress Custom Fields

Now, values are added but how to grab them and display on front-end? Well, there quite a few inbuilt functions which can help you to retrive custom field data. Below are two functions for the same purpose.

1. the_meta()
2. get_post_meta()

If you use, the_meta() function, output of this should be something like this,




Now, if you want to grab value of any particular custom field, you should use, get_post_meta() function.


get_post_meta($post_id, $key, $single);

Here,
$post_id is ID of the post or page.
$key is the string name of your meta value.
$single is eithre ‘true’ or ‘false’. Here ‘true’ will return string result and ‘false’ will return a Array as a value. By default value is ‘false’.

Simple Usage




Above code will fetch price meta field’s value and store it in the variable $price and we can easily display its value.

Loop Example
We can use this function inside WordPress loop where posts are displayed. So, we can display any meta-data attached to the posts with loop itself. We are also using the same thing to display thumbnail images besides post on our blog. Code for it is as below :


ID, 'thumbnail', true) ) : ?>
    
        <?php the_title(); ?>
    


So, get ready to display some meta-data along-with the post. It’s damn useful and believe me you can turn you site in something extra ordinary with this functionality. Happy Blogging.

Leave a Comment

Previous post:

Next post: