Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

When creating custom page templates, how do I get the value of a custom field of the displayed page?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Use the get_post_meta function.

share|improve this answer
add comment

WordPress Custom Fields

WordPress custom fields contain a key and a value. To get both <?php the_meta(); ?> will return

<ul class='post-meta'>
<li><span class='post-meta-key'>your_key:</span> your_value</li>
</ul>

To return a value stored for a specific key use:

<?php get_post_custom_values('my_key', $post_id); ?>**

If a post contained more than 1 value for the same key you can use a foreach loop to output all of them i an array:

<?php    
  $mykey_values = get_post_custom_values('my_key');
  foreach ( $mykey_values as $key => $value ) {
    echo "$key  => $value <br />"; 
  }  
?>

This will return:

0 => First value 
1 => Second value
2 => Third value 

To return an array of keys within all custom fields use:

<?php get_post_custom_keys($post_id); ?> 

Adding custom fields to a post:


alt text

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.