How to display custom field on homepage

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.

<?php 
$meta = get_post_meta( get_the_ID(), 'Story' );
if( !empty($meta) ) {
    echo $meta[0];
}?>

2 Answers
2

Try this:

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

    $name=trim($name);
    $prefix=''; // only if you need this
    $data=NULL;

    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);
    else
        $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);
}
endif;


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.

Leave a Comment