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'm writing a plugin and am trying to figure out how to add data to the end of a post based on some Custom Meta Information.

So i've done this so far:

add_filter('the_content', 'AppendMeta');

And here is the "AppendMeta" function

AppendMeta($content) {
    echo $content; // Echo out post content
    $PersonName = get_post_meta($post->ID, 'PersonName', true);
    echo 'Person: ' . $PersonName;
}

That code works if I replace $post->ID with the id of the post, but I need it to work based on the post the user is currently navigating. How would I pass the post id in as a parameter? $post->ID doesn't work in this scenario and I can't find out why.

share|improve this question
1  
Quick note: when hooking into a filter hook your function should return the filtered variable instead of echoing it out. –  Bainternet May 5 '12 at 10:24
    
Is that convention or is there a reason why? –  Talon May 5 '12 at 16:52
    
its convention for a reason, filter hooks let you alter/modify a value and expect that value to be returned, that's just how they work. –  Bainternet May 6 '12 at 9:54
add comment

2 Answers 2

up vote 2 down vote accepted

Nevermind, found out I can use get_the_ID();.

This function will return the post id inside the the_content filter. The function simply declares the global $post object and returns its ID.

add_filter('the_content', 'wpse51205_content')
wpse51205_content($content) {
    echo $content; // Echo out post content
    $PersonName = get_post_meta(get_the_ID(), 'PersonName', true);
    echo 'Person: ' . $PersonName;
}

If you don't want to use get_the_ID(), you simply need to declare the $post object global before using it:

add_filter('the_content', 'wpse51205_content')
wpse51205_content($content) {
    global $post;
    echo $content; // Echo out post content
    $PersonName = get_post_meta($post->ID), 'PersonName', true);
    echo 'Person: ' . $PersonName;
}
share|improve this answer
    
Oh yeah, good to know, probably more reliable that way. –  Talon May 5 '12 at 16:51
    
get_the_ID() is still meant to be used inside the loop only. It might work for you well on single pages but a fully reliable way is to access global $post variable only like I said in my answer. –  Ashfame May 6 '12 at 6:48
add comment

the_ID() is only supposed to be used inside the loop, else you can't rely on it. Better use the $GLOBALS['post'] object inside your function call.

share|improve this answer
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.