Wordpress custom field return values
I am trying to iterate a custom field key (value such as the URL given when editing a post) back into a document. Here's the general 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); ?>
This prints nothing - any ideas?
The custom field in the post is already a "function", no CSS or Javascript issue, it just doesn't return a value.
+2
source to share
2 answers
Please add global $post;
before you call the function get_posts()
and don't use $ post naming in your foreach () loop and then see if it works or not! If it fails, just use this code:
<?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;
?>
+2
source to share