I’ve been looking for a non-intrusive way to insert text before any of my WordPress Single Posts and Pages. In the past, I modified the themes directly, but since I didn’t own the themes I was using, anytime I updated the theme, I would lose all my changes.
I had found I can insert text at the top and bottom of my pages using add_action. For example:
add_action( 'get_footer', 'echo_hello_world' );
function echo_hello_world( $post )
{
echo "hello world";
}
would add the phrase “hello world” to the bottom of every single page on my blog. You can find a list of tags on WordPress’ Action Reference page.
One of the things I wanted to do was insert some text beneath my header, but before my post. I had found get_template_part_content would do the trick on Pages, but not Single Posts. After I failed at finding a solution online, I looked into how the code differed between Pages and Single Posts.
Single Posts were calling:
get_template_part( 'content-single', get_post_format() );
while Pages were calling:
get_template_part( 'content', 'page' );
So I wondered if get_template_part_content_single
would work, but nothing happened. I then tried get_template_part_content-single
, lo and behold, it WORKED! Given that Google has 0 search results with that exact phrase, I’m guessing no one’s discovered this action tag or at least posted about it publicly.
So my code ended up looking like:
add_action( 'get_template_part_content', 'echo_hello_world' );
add_action( 'get_template_part_content-single', 'echo_hello_world' );
function echo_hello_world( $post )
{
if( is_single() || is_page() )
{
echo "hello world";
}
}
As a bonus, here’s a tag you can use to insert text between your post and the comments section: comments_template