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.

1
  • 1
    If you get it to echo only the $post->ID does that return anything. The syntax is correct. Stupid Question, but you want the contents of feature to be in the Stlye section? Have you looked at the source behind the page? Commented Oct 21, 2009 at 22:24

2 Answers 2

2

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;
?>
Sign up to request clarification or add additional context in comments.

Comments

0

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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.