• I’m attempting to use the get_post_custom_values() function to retrieve a custom field for a post titled “news-image”.

    I want to use this variable as the src attribute for an <img />

    Here is my code:

    <?php
       $imgSrc = get_post_custom_values('news-image');
    ?>
    <img src="<?php echo $imgSrc[0]?>" />

    In the HTML the src continues to be null. You can view my page at https://metroiceblog.net

    What am I doing wrong?

Viewing 5 replies - 1 through 5 (of 5 total)
  • get_post_meta($post_id, $key, $single);

    $key = your custom field name (ie news-image)
    $single = true

    so for you it should be

    $imgSrc = get_post_meta($post_id, 'news-image', true);

    if you want to use the get_post_custom_value function, your problem probably (can’t tell without the source) is because you have it outside of the loop

    Thread Starter dannym

    (@dannym)

    <div id="content" class="widecolumn clearfix">
    
            <div id="left">
                    <div id="headlines">
                            <h3>Top Headlines</h3>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
     <!-- If the post is in the category we want to include it -->
     <?php if (!(in_category('3'))) continue;
    
            if($i == 0){
    $imgSrc = get_post_meta($post_id, 'news-image', true);
    ?>
     <div class="post">
            <img src="<?php echo $imgSrc[0] ?>">
      <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    
      <small><?php the_time('F jS'); ?> - By <?php the_author(); ?></small>
            <hr />
      <div class="entry">
             <?php the_excerpt(); ?>
     </div>
    
      <p class="postmetadata">Posted in <?php the_category(', '); ?></p>
     </div> <!-- closes the first div box -->
    <div class="clearfix"></div>
     <?php
            } else if($i < 3 && $i > 0){ ?>
                    <h2 class="clearfix"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php   }
            $i++;
     endwhile; else: ?>
     <p>Sorry, no posts matched your criteria.</p>
     <?php endif; ?>
    ...

    This doesnt seem to work either. Thank you for your helpp, I’m very gracious!

    Try <img src="<?php echo $imgSrc;?>">.

    Thread Starter dannym

    (@dannym)

    Thanks esmi, unfortunately, that solution didn’t work either. Does it matter that I’m using a WPMU codebase?

    sorry I screwed up. should be:

    $imgSrc = get_post_meta($post->ID, 'news-image', true);

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Using custom fields in the template’ is closed to new replies.