How to add something to the_content in WordPress using PHP

Sometimes we need to add additional text or elements to the_content in WordPress. This can include links, icons, shout outs, author biographies, and so forth. I wanted to add an Apple Podcasts badge underneath each post in my podcast categories, adding a link to the badge, depending on the category. I’ll elaborate how I did this in a later post.

Right now, let’s have a look at how we can add elements to the content retrieved from WordPress. This should work independently of your theme, and no theme-file-hacking is necessary to accomplish this.

All we need to do is intercept the_content as it is requested, append our elements and return an amended version of the_content. Let’s see how this works.

Intercepting the_content

When the_content is requested from the database by WordPress, we can hook into a filter and intercept it. We can do this by creating a function like this:

function prefix_add_content ($content){
	
	return $content;
}
add_filter ('the_content', 'prefix_add_content');

By itself this won’t do anything, but it illustrates the principle nicely. Add this to your child theme’s functions.php file, or use it in plugins as appropriate. $content is a variable that contains everything that is printed after the title and before the comments.

Injecting new content

Inside our function, we can do anything we like with the content now. I’ll add some text before and after to demonstrate how this works.

function prefix_add_content ($content){
	
        $before = "This comes before the content.";
	$after = "This comes after the content (like my Podcast badge).";
	$content = $before . $content . $after;

	return $content;
}
add_filter ('the_content', 'prefix_add_content');

Here we declare two variables with pre and post content text. These could include links and other HTML elements, even inline CSS classes so you can later style those elements independently.

Now we concatenate all variables using the . operator in PHP, putting it all into the $content variable again before returning it. That’s all the magic we need right now.

Since this is PHP, you can do anything you like inside that function, like checking if the content is appended / prepended to the correct category or if other conditions are met.

Thanks to WP Developers for putting me on the right track during my investigations 🙂

You can leave a comment on my original post.