Home Web Development PHP Solution to: How do I automatically append/prepend text to the start of...

Get social!

I created a new posts category today, called “Riddle Me This”. The category holds posts for my questions to which I can’t find the answers. Hopefully there won’t be many entries in it.

I decided to add an explanation to the top of each post within this category, stating it’s purpose, which is to put my unanswered questions out on the Internet, hoping that someone else can answer them. Here’s how I did it.


Let me first say that there seems to be a lot of plugins dedicated to custom category templates. I ignored all of them. What I did was download Custom Post Template, a simple but powerful plugin that adds a dropdown box of templates to the Add/Edit Post page. Of course, there are no templates initially except the default template — you have to create them. To do so, make a copy of single.php in your theme folder (I’m working with WordPress 3.7.1, currently). I named my template riddleme.php. Then open the copied file in your favorite text editor and get to editing.

First, you have to add a few lines at the top of your new template (this is how the plugin IDs it). Something like this will suffice:


This needs to go inside your <?php...?> tags, of course.

For my needs, I just wanted to prepend some text to the start of each post that used this template. Here’s what I added:


I’m not going to explain the code in detail (if you don’t understand it, google wordpress add_action), except to say that the add_action() function causes the show_riddlemethis_text() to execute before WP renders the contents of the post. Within that function you can alter the post contents as as you see fit — it’s in the $content variable.

If you’ve done everything right, when you go to the Add/Edit Post page, you should see a dropdown box below the text editor, and your custom theme should be in it. Select it. When you save the post the changes you made in the template will be displayed on the post page.

Bad Behavior has blocked 160 access attempts in the last 7 days.