MetalParchment
MetalParchment

Reputation: 75

Fetch custom field data for a specific blog post

I want to output the metadata from a custom field in WordPress post.

On this page if WordPress codex I found the following instruction:

To fetch meta values use the get_post_meta() function:

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

I am trying to do it this way:

<?php
get_post_meta(1, 'Currently Reading',true);
?>

But nothing gets output in the browser.

What's the proper way to output the content of the custom field?

Upvotes: 2

Views: 439

Answers (3)

AndyWarren
AndyWarren

Reputation: 2012

The easiest way to do this is this:

<?php echo get_post_meta($post->ID, 'your_meta_key', true); ?>

On your post or page editor, you can go to "Screen Options" in the top right corner and check the box to display "Custom Fields". This will allow you to see the meta keys available. Just copy the name of the meta key into your get_post_meta call in the spot above where it says "your_meta_key". Don't change the $post->ID as that is global.

Upvotes: 1

jshbrmn
jshbrmn

Reputation: 1787

get_post_meta(1, 'Currently Reading',true); will only get the values, you need to store it somewhere and output it properly. One way to do this is to store the function return values into a variable like so:

<?php $custom = get_post_meta( 1, $key, $single ); ?>

Then you can output it with a print or echo like so:

echo $custom;

Something to note, try using a value $post_id for the first argument. This will grab the current post id.

Upvotes: 0

Darren
Darren

Reputation: 13128

Taken from that page linked

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

so you'd need to access it through the $meta_values return object.

Like so:

<?php 
print_r($meta_values);

print 'The ID is: ' . $meta_values->ID;
?>

Upvotes: 0

Related Questions