views:

163

answers:

2

I'm trying to echo the key of a custom field (value, such as a URL set while editing a post) back into the document. Here's the overall code:

  <div id="feature" class="clearfix">

            <?php  
             $feature_post = get_posts('category=3&numberposts=1');
      foreach( $feature_post as $post ) : 
        ?>
      <div class="feature_post" style='<?php echo get_post_meta($post->ID, 'feature', true); ?>'>
       <h2><?php the_title(); ?></h2>
      </div>
      <?php 
       endforeach; 
      ?>

      </div>

Specifically, this is the line of code:

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

That doesn't print anything - any ideas?

The custom field on the post is already 'feature', there's no CSS issues or Javascript, it's just not returning the values.

+6  A: 

Please add global $post; before you call get_posts() function and don't use $post naming in foreach() loop, then see if it works or not! If failed simply use this code instead:

<?php
    $loop = new WP_Query('cat=3&showposts=1');
    if($loop->have_posts()): 
        while($loop->have_posts()): $loop->the_post();
?>
            <div class="feature_post" style="<?php echo get_post_meta($post->ID, 'feature', true); ?>">
                <h2><?php the_title(); ?></h2>
            </div>
<?php
        endwhile;
    endif;
?>
Sepehr Lajevardi
A: 

Not sure that category=3 works, but use cat=3 in your get_posts statement.

Also need setup_postdata($post); after your foreach statement.

Sepehr Lajevardi's solution should also work nicely ;)

Michael