It sounds like you want a filter on the_content
.
function add_content_wpse_97277($content) {
global $post;
if ($post->ID == 123) {
$content .= 'additional content';
}
return $content;
}
add_filter('the_content','add_content_wpse_97277');
I don’t know what conditions you need though. You did not explain that in the question. The above should match a post with an ID
of “123”.
For index pages you may need to add the same callback to the the_excerpt
hook. You can control where the function adds content with template tags like is_home
or is_single
.
Honestly, this is how you should be adding your content both above and below the post. Echoing content from an action like the_post
can work but is also a good way to get yourself in trouble. In this case I’d say it is particularly dangerous. the_post
runs inside setup_postdata
which does frequently run inside a loop that echoes content immediately, but if that function– setup_postdata
— runs inside a Loop that doesn’t echo immediately, for example to build a string, your markup will make a mess. There is also loop_start
and loop_end
but I don’t think those are what you want.
Having seen your question and your comments and considered them, I have to say that your basic approach is wrong. You should be using the the_content
and the the_excerpt
, and/or possibly the get_the_excerpt
filter as well.
Unfortunately filtering the content/excerpt doesn’t do what I need it
to do. There are often divs or footers added to a post (in the loop)
below the excerpt/content. That means filtering the content/excerpt
would not make my content appear at the bottom of the post in the
loop. Thanks though, your help is appreciated!quoted from a comment below
I doubt there is a reliable way to do what you want. The only filter you have to work with that I can see is the_post
. You could use that to insert between posts by tracking which post of the Loop you are on and inserting content conditionally. That is:
- If post number 0, then insert the begin
<div>
- If post number 1, then insert
</div>
and<div>
- …
- If last post, then insert
</div>
But again, you are going to make a mess echo
ing content from the the_post
filter when setup_postdata
is used in a context that does not echo
content immediately– for example, in a context where a string is being built and returned.