Reputation: 1029
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.
Upvotes: 2
Views: 607
Reputation: 507
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 ;)
Upvotes: 0
Reputation: 18505
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;
?>
Upvotes: 2