Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've search all over for a solution to this but can't seem to find anything that does exactly what I want it to.

Basically what I want to do is display a particular div within a post based on the value of a specific custom field.

For example;

If the value of the "featured" custom field is "1" then I want to be able to show a div within single.php for that particular post

But if the value of the "featured" custom field is anything other than 1 then I don't want anything to appear.

Does that makes sense?

share|improve this question
    
How are you adding this particular <div> to the post? Or is your question more like "How do I add a <div> to a post based on a meta field value?" –  s_ha_dum Nov 22 '12 at 19:50
    
It would be added to the end of the post. So if the meta value is '1' then "sample-div" would be added after all the user created conent –  Dean Elliott Nov 22 '12 at 19:56
    
Have you searched the Codex? Have you tried to implement any of those examples into your theme? –  brasofilo Nov 22 '12 at 23:07
add comment

1 Answer

up vote 1 down vote accepted

Then you need a filter on the_content.

function add_conditional_div($content) {
    global $post;
    $meta_field = get_post_meta($post->ID, 'your-field-name', true);
    if (1 === $meta_field) {
        $content .= '<div>whatever</div>';
    }
    return $content;
}

The 1 value, of course, is whatever should match your meta_field.

http://codex.wordpress.org/Function_Reference/get_post_meta

http://codex.wordpress.org/Function_Reference/the_content

You could also edit your theme files directly or make a child theme. The latter is highly encouraged if you are editing a theme you didn't create.

share|improve this answer
    
That didn't seem to work for me. I don't actually want it to be part of the content, just to come after the loop –  Dean Elliott Nov 22 '12 at 21:34
    
@DeanElliott, your description of the problem in your question does not match the comment you just posted. "div within a post based on the value of a specific custom field" strongly implies in the Loop not after it. –  s_ha_dum Mar 18 '13 at 17:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.