Menu bar

Sunday 4 January 2015

Working with custom fields

USING CUSTOM FIELDS


This function returns the values of the custom fields with the specified key from the specified post. It is a wrapper for get_metadata('post').

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


$key is a string containing the name of the meta value you want.


If only $post_id is set it will return all meta values in an associative array.
If $single is set to false, or left blank, the function returns an array containing all values of the specified key.
If $single is set to true, the function returns the first value of the specified key (not in an array)


Dump out all custom fields as a list
<?php the_meta(); ?>

Display value of one specific custom field
<?php echo get_post_meta($post->ID, 'key', true); ?>
"key" would be ID value of custom field


Display multiple values of same custom field ID
<?php $key_val = get_post_meta($post->ID, 'key_val', false); ?>
<h3>This post inspired by:</h3>
<ul>
<?php foreach($key_val as $key) {
echo '<li>'.$key.'</li>';
} ?>
</ul>


Display custom field only if exists
<?php 
    $url = get_post_meta($post->ID, 'reference-URL', true); 

if ($url) {
   echo "<p><a href='$url'>URL</a></p>";
}
?>

No comments: