In the previous tutorial Add custom fields, We added custom fields. In this tutorial we will learn how to get those custom fields values.

Displaying Custom Fields

To display custom fields in each post use the_meta() in wordpress loop.

So if we added custom fields with name and key values as

NameValue
website www.snilesh.com
emailabc@snilesh.com

Then the result will be

<ul class='post-meta'>
<li><span class='post-meta-key'>website:</span> www.snilesh.com</li>
<li><span class='post-meta-key'>email:</span> abc@snilesh.com</li>
</ul>

Get Custom Values/Keys

Returns a multidimensional array with all custom fields of a particular post or page.

This function is useful when you are added values using same custom field key.

Usage:

<?php get_post_custom($post_id); 
//$post_id (optional) The post ID whose custom fields will be retrieved. by default it is current post.
?>

In this example if we added websites like www.mstindia.com, www.snilesh.com,www.google.com using same “website” as key/name.

Then to retrieve all values entered using website as customfield name/key function will be used as

<?php
  $custom_fields = get_post_custom($post_id);//Current post id
  $my_custom_field = $custom_fields['website'];//key name
  foreach ( $my_custom_field as $key => $value )
  echo $key . " => " . $value . "<br />";
?>

So the output will be

0 => www.mstindia.com
1 => www.snilesh.com
2 => www.google.com

Function get_post_meta()

One more function is there which is used to retrieve custom fields values it is get_post_meta().

You can use this function as

<?php $meta_values = get_post_meta($post_id, $key, $single); ?>

Where $post_id is the post id / page id whose custom fields we are retrieving. $key is the key name and $single is (boolean) (optional) If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields.

Return Values

1]If $single is set to false, or left blank, the function returns an array containing all values of the specified key.
2]If $single is set to true, the function returns the first value of the specified key (not in an array).

Usage

<?php
//in this example we will retrieve website url
$website_url=get_post_meta($post->ID,'website',true);
?>