I am new to custom fields thing. I am working on a movie review site. And wants to add movie story or plot field, I have successfully added the custom field named Story and its content is displaying on single.php. However, can I display same on index.php? Below is my code.

$meta = get_post_meta( get_the_ID(), 'Story' );
if( !empty($meta) ) {
    echo $meta[0];
  • Please describe more "Story" is right name of meta. and whats u store in this field. this one array value stored? – ravi patel Oct 20 '15 at 11:56
  • Yes "Story" is my field name and yes array value stored. – user235377 Oct 20 '15 at 18:03

Add this code on content.php because of index.php content comes from this file.

if u call outside of post use 
global $post;  
$meta = get_post_meta($post->ID , 'Story', true);

OR inner loop

$meta = get_post_meta(get_the_id(), 'Story', true);

if( !empty($meta) ) {
    echo $meta[0];
  • Not working, i have already tried this. – user235377 Oct 20 '15 at 11:52

Try this:

if ( ! function_exists( 'customField' ) ) :
function customField($name, $id=false, $single=false){
    global $post_type, $post;

    $prefix=''; // only if you need this

    if($id!==false && !empty($id) && $id > 0)
        $getMeta=get_post_meta((int)$id, $prefix.$name, $single);
    else if(isset($post->ID) && $post->ID > 0)
        $getMeta=get_post_meta($post->ID,$prefix.$name, $single);
    else if('page' == get_option( 'show_on_front' ))
        $getMeta=get_post_meta(get_option( 'page_for_posts' ),$prefix.$name, $single);
    else if(is_home() || is_front_page() || get_queried_object_id() > 0)
        $getMeta=get_post_meta(get_queried_object_id(),$prefix.$name, $single);
        $getMeta=get_post_meta(get_the_id(),$prefix.$name, $single);

    if(isset($getMeta[0])) $data=$getMeta[0];

    if($data===false || !is_numeric($data) && (empty($data) || is_null($data))) return NULL;

    $return = preg_replace(array('%<p>(<img .*?/>)</p>%i','%<p>&nbsp;</p>%i','/^\s*(?:<br\s*\/?>\s*)*/i'), array('$1','',''),$data);

    return (!empty($return)?$return:NULL);

echo customField("story"); // Default
echo customField("story", 55); // With custom page ID

This code work great becouse I build this for my works. If return empty, in place where you setup pharameters, you not save your data. Also be careful about prefix of your metabox if you use it.

  • Nope, still not working. – user235377 Oct 20 '15 at 17:41
  • Are you save data in metabox? – Ivijan Stefan Stipić Oct 21 '15 at 16:48
  • Yes i did saved the data. – user235377 Oct 21 '15 at 18:05
  • I know is old post but I just made update. This code search deeply inside WP and get custom field value on any place inside theme. I just have the same issue and find this working solution. – Ivijan Stefan Stipić Aug 1 '16 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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