Posted on

How to insert content at the beginning or end of a WordPress post

I am trying to optimise Adsense earnings of my WordPress website Smartroman.co.uk by inserting ads at the beginning and end of the post. If you want to do something similar, insert an advertisement, image, or additional paragraphs to the beginning or end of the post, you may use following trick.

Basically, you need to use so called filters and add a php code to one of your WordPress Theme files. The code needs to be inserted into functions.php file that is located in Website-root/wp-content/themes/name-of-your-theme/. First download this file using FTP client. I think it is a good idea to copy it into two locations of your computer. If something goes not according to the plan and your WordPress website breaks down, you will be able to easily restore it using the original file 🙂

If you want to have some additional content just below the heading, but before the main content, add the following code to the file:

add_filter( 'the_content', 'inserting_above_content' );

function inserting_above_content( $content ) {
 
    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        return "<p>This will go above the content...</p>" . $content ;
   }
    return $content;
}

And a very similar code, if you prefer to put something at the end of the main content, just above the comments:

add_filter( 'the_content', 'inserting_below_content' );

function inserting_below_content( $content ) {
 
    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        return $content . "<p>This will go below the content...</p>" ;
   }
    return $content;
}

After you added the code, save the file and transfer it back to the server. Your FTP client will ask you if you want to overwrite the existing functions.php file. Choose ‘Yes’. Now, if you refresh your page and the things you have inserted should be visible in all the posts.

One last thing. Please keep the file on your computer because if the WordPress Theme you are using will be updated, you your modified file will be overwritten and you will have to upload your file again. You can use this problem by using so called Child Theme, please try to find some more information about it on the Internet.

I hope you have found it useful. Please let me know if you have any questions or perhaps want to insert some content in other places of your WordPress website.

Leave a Reply

Your email address will not be published. Required fields are marked *

four × two =