Please disable your Ad Blocker to better interact with this website.

BLOG

See what we're whipping up!

I’ve come across numerous articles and forum threads on the internet teaching and discussing how to add code before the_content via a custom function. Funny enough, I’ve also seen many others on how to add code after the_content via, yet again, another custom function. Well, prepared to be amazed! Because, today I’m going to tell you how to do both, at the same time! That’s right, at the same time! Whoo! Cheer! Oh, it’s not that exciting. Well, okay then. I’ll just go on with it.

Wait. Before we get started, and if you haven’t read it yet, you might want to checkout my Sweet WordPress Functions post, because I show you how to create your own plugin for custom functions and stuff. That way, your functions are safely tucked away and won’t be written over in you functions.php file when you update your theme. Also, if you do something wrong and your code goes haywire, you can just disable the plugin and viola, you’re saved! Alright, I’m actually moving on now.

First thing is first, we have to create a function.

function wpdev_before_after($content) {

}
add_filter('the_content', 'wpdev_before_after');

So, we have our function now and it’s hooking into the_content(). Now, we need to feed it something! First, we’re going to use a variable to define our output before the_content, and then we’re going to use a variable to define our output after the_content.

$beforecontent = 'This goes before the content. Isn\'t that awesome!';
$aftercontent = 'And this will come after, so that you can remind them of something, like following you on Facebook for instance.';

Alright, now we have our variables with our content. Let’s do some reorganization! Oh, how I love the simplicity of it.

$fullcontent = $beforecontent . $content . $aftercontent;
return $fullcontent;

Seriously, that’s it! So, with it all together now!

function wpdev_before_after($content) {
    $beforecontent = 'This goes before the content. Isn\'t that awesome!';
    $aftercontent = 'And this will come after, so that you can remind them of something, like following you on Facebook for instance.';
    $fullcontent = $beforecontent . $content . $aftercontent;
    
    return $fullcontent;
}
add_filter('the_content', 'wpdev_before_after');

Bam! Boom! Content before AND after the_content. You can use this for all kinds of stuff! Share buttons, Reminders to check you out on Facebook, Twitter, etc. Anything! Oh, and a hint, you can add more variables and add them to the $fullcontent string. How you arrange them in the string is how they’ll be output. Let me know if you have any questions or need any help in the comments below, and as always, have a great day!

Update

You can also add conditionals to your function, so that it only outputs the added content on pages only, posts only, certain pages or certain posts, etc. The conditional you use is up to you. Don’t forget though to fill out the else statement with the content output! If you restrict content additions to posts only and don’t return your content for all other content, then it won’t be output. See the blow example for the correct code.

function wpdev_before_after($content) {
    if(is_page() || is_single()) {
        $beforecontent = 'This goes before the content. Isn\'t that awesome!';
        $aftercontent = 'And this will come after, so that you can remind them of something, like following you on Facebook for instance.';
        $fullcontent = $beforecontent . $content . $aftercontent;
    } else {
        $fullcontent = $content;
    }
    
    return $fullcontent;
}
add_filter('the_content', 'wpdev_before_after');

Update in Response to Mohamed Below:

Mohamed commented below and asked if you can randomize what content is displayed before and after the content. Since we’re storing the content in variables, we can actually do this fairly easily by generating a random number and then using some more if/else statements. So, for example, you could do something like this:

function wpdev_before_after($content) {
    if(is_page() || is_single()) {
        $rand1 = rand(0,1);
        $rand2 = rand(0,1);
        
        // If/Else for Before
        if($rand1 == 1) {
            $beforecontent = 'This goes before the content. Isn\'t that awesome!';
        } else {
            $beforecontent = 'Or this could go before the content, depending on whether or not a 0 or a 1 is generated.';
        }
        
        // If/Else for After
        if($rand2 == 1) {
            $aftercontent = 'This could be an email sign-up form at the end of the content.';
        } else {
            $aftercontent = 'Or it could be a Facebook like button.';
        }
        
        // Output
        $fullcontent = $beforecontent . $content . $aftercontent;
        
    } else {
        $fullcontent = $content;
    }
    
    return $fullcontent;
}
add_filter('the_content', 'wpdev_before_after');

Update in Response to Jason Below:

Jason commented below and asked if you can set specified post dates to display before and after the content and the answer is yes. It just requires a bit more logic with some new information that we’re going to grab. We’re setting up a start date via a variable, as well as an end date, and we’re grabbing the post publish date, the current date, and the date from 60 days ago. I’ve included all of the logic for each one under a heading, so you can delete what you don’t want and use what you do.

function wpdev_before_after($content) {
    if(is_page() || is_single()) {
    
        // Date Variables
        $startdate = '20170102'; // Format YEAR/MONTH/DAY
        $enddate = '20170516'; // Format YEAR/MONTH/DAY
        $currentdate = date('Ymd'); // Format YEAR/MONTH/DAY
        $past60days = strtotime('-60 days');
        $postdate = get_the_date('Ymd', get_the_id());
    
        // If you want to display before and after content for a specific time period
        if($currentdate > $startdate && $currentdate < $enddate) {
            $beforecontent = 'This goes before the content. Isn\'t that awesome!';
            $aftercontent = 'This could be an email sign-up form at the end of the content.';
        } else {
            $beforecontent = ''; // Don't display anything anymore.
            $aftercontent = ''; // Don't display anything anymore.
        }
        
        // If you want to display before and after content on posts from a specific time period
        if($postdate > $startdate && $postdate < $enddate) {
            $beforecontent = 'This goes before the content. Isn\'t that awesome!';
            $aftercontent = 'This could be an email sign-up form at the end of the content.';
        } else {
            $beforecontent = ''; // Don't display anything anymore.
            $aftercontent = ''; // Don't display anything anymore.
        }
        
        // If you want to display before and after content on posts published from 60 days ago until now
        if($postdate > $past60days) {
            $beforecontent = 'This goes before the content. Isn\'t that awesome!';
            $aftercontent = 'This could be an email sign-up form at the end of the content.';
        } else {
            $beforecontent = ''; // Don't display anything anymore.
            $aftercontent = ''; // Don't display anything anymore.
        }
        
        // Output
        $fullcontent = $beforecontent . $content . $aftercontent;
        
    } else {
        $fullcontent = $content;
    }
    
    return $fullcontent;
}
add_filter('the_content', 'wpdev_before_after');
Share this article: Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUponPin on PinterestEmail this to someone

18 comments

  • If my new content is in a external file php, How call it? Thank you 🙂

    Reply
    • Hello Eva,

      Thanks for the question! You can use get_template_part(‘file-name’);

      If your file is custom-single.php, for example, it would be get_template_part(‘custom-single’);

      Reply
      • Hi. Thank you by your answer but I’m tried with this method and dont’t work.
        The content of file prints twice: Before the content (always before) and at the end of all code of page (after footer) 🙁

        Reply
        • Hey Eva,

          Could you please post your code? Thank you!

          Reply
  • Hi, I tried to put your code inside the function.php in twenty sixteen theme but it doesn’t work. any suggestion how to use your wonderful idea inside function.php? Thanks a lot

    Reply
    • Sorry for the late response! But, it still works. The site was formatting the single quotes incorrectly. I’ve fixed that issue, so you should be good to go.

      Reply
  • Hello, I added your code as a custom plugin. But it will not show up. Am I doing something wrong?

    function wpdev_before_after($content) {
    if (is_single()) {
    $beforecontent = ‘ksjhs’;
    $aftercontent = ‘sddfsfsdfs’;
    $fullcontent = $beforecontent . $content . $aftercontent;
    return $fullcontent;
    }
    }
    add_filter(‘the_content’, ‘wpdev_before_after’);

    Reply
    • Hey Juan,

      This function still works as I use it across many sites. For some reason the site was adding curly quotes, instead of straight. I’ve updated the code snippets plugin so that it’s works much better now. 🙂

      Reply
  • We need to add rotate random content with priority numbers before and after content
    How we can use this function and add_filter with this parameters ?

    Reply
    • Hey Mohamed,

      Sorry I missed this! You can add rotating of random content by using a random number generator and some if/else statements around the $beforecontent and $aftercontent variables. I’ll add an update to the post.

      Reply
  • What if you wanted to filter by dates of posts published? So, say maybe you were running a promotion during a period of time. Or you wanted from a certain post day back to say a particular message?

    Reply
    • Hey Jason, thanks for commenting! I’ve replied above. 🙂

      Reply
  • what if we want to put some thing between the_content. so for example the content is “abcdef” . i want to put XYZ after abc. is it possible ?

    Reply
    • Yes, it is, but that’s getting quite complex, so it’s not something I can really outline here. I may do it in the future in another post to extend on this concept. Thanks for the question!

      Reply
  • This is the closest post I have found that helps with my idea. I am wanting to insert an opening schema div right above the content of my wordpress pages and a closing div for that right under the content. I am also wanting to insert a google analytics code in the header of the site with this plugin I am making (both it and the schema type will pull a custom global option I have made for this plugin). What I am wondering is how do I get it removed when the plugin is un installed. I am super fresh into php and am majorly new.

    Here is what I have so far (the global options are not yet in there)

    (function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,’script’,’https://www.google-analytics.com/analytics.js’,’ga’);

    ga(‘create’, ”, ‘auto’);
    ga(‘send’, ‘pageview’);

    <?php
    }
    }

    // INSERT HEADER SCHEMA DIV IN THE CONTENT
    function hawp_schema_before_after($content) {
    if(is_page() || is_single()) {

    // Opening body schema div and productontology
    $beforecontent = '
    <div id="” itemscope itemtype=”http://schema.org/” itemref=”-Location”>
    <?php if(get_option('hawp_opt_productontology')) {
    echo '’;
    } ?>
    ‘;

    // Closing body schema div
    $aftercontent = ”;

    // Displays opening schema div, productontology and closing schema div
    $fullcontent = $beforecontent . $content . $aftercontent;

    } else {

    // Displays only the content
    $fullcontent = $content;
    }

    // Displays opening schema div, productontology and closing schema div
    return $fullcontent;
    }
    add_filter(‘the_content’, ‘hawp_schema_before_after’);

    Reply
    • As you can see, yes the form on this site did cut off the top info for the google analytics code, but I think you get the point I am getting at

      Reply
    • Hey Evan,

      Thanks for commenting! For the Analytics code, in order to place it into the head, you’d want to use the wp_head hook. So, it would look something like this:

      function wpdev_head_code() {
      echo ‘ANALYTICS CODE’;
      }
      add_action(‘wp_head’, ‘wpdev_head_code’, 1);

      The ending number in the action is a priority, so you can set it to 1 if you want it to appear high in the head, or a lower number like 99, if you want it to appear lower in the head.

      If you place these functions, as well as the before and after content filters, in a plugin, once it’s deactivated the code will be removed. That’s the beautiful thing about functions in plugins. Most people would go into single.php and manually code stuff before and after the content, but running through a function, in a plugin, allows you a lot more flexibility, especially when updating parent themes and such. Let me know if you have any other questions!

      Reply