Forums

How to automatically add permanent text to each post? (6 posts)

  1. hakaii
    Member
    Posted 2 years ago #

    I would like to start each of my posts with this text: (Biology News, posted on [the date]) and then have the text of the post follow immediately without a line break. Rather then inputting this into every post, is there a way to change the post template to have this done automatically? I have played around with the_meta tag but can't seem to find a solution.

  2. s_ha_dum (was apljdi)
    Member
    Posted 2 years ago #

    If you are posting the same text on every entry you don't need to mess with meta content, just edit the theme's functions.php to add the following:

    function add_before_content($content) {
      return '<p>(Biology News, posted on ['.get_the_time().'])'.ltrim($content,'<p>');
    }
    add_filter('the_content', add_before_content);

    Pretty sure that's right... :)

  3. hakaii
    Member
    Posted 2 years ago #

    Thanks apljdi, that works almost perfectly! The only problem I find is that when the post starts with a linked word, i.e. the HTML code starts with a <a href it strips away the '<' and thus screws up the code.

    Also, how do I use the date instead of the time? I tried to replace get_the_time() with get_the_date() but that doesn't seem to work...

  4. jonradio
    Member
    Posted 2 years ago #

    get_the_time is correct, but needs a parameter:
    get_the_time('l, F j, Y')

    See here http://codex.wordpress.org/Function_Reference/get_the_time and here http://codex.wordpress.org/Formatting_Date_and_Time for more details.

    As for the add_before_content function, I haven't used it. But would have changed the single.php template file in my Theme instead. Only because I have experience changing templates. And because I started out my WordPress journey using the second edition of WordPress for Dummies, where the author describes template file changes as the way to do almost everything.

    Note that single.php is only used when displaying a single post, and will not alter what is displayed in the excerpts of posts shown on the main page -- index.php does that.

  5. s_ha_dum (was apljdi)
    Member
    Posted 2 years ago #

    The only problem I find is that when the post starts with a linked word, i.e. the HTML code starts with a

    Of course it does... my mistake. preg_replace should work better.

    function add_before_content($content) {
      return '<p>(Biology News, posted on ['.get_the_time().'])'.preg_replace('/<p>/','',$content,1);
    }
    add_filter('the_content', add_before_content);

    I haven't tested with all of the possible items that might start a post-- images, video, etc.

  6. hakaii
    Member
    Posted 2 years ago #

    Works like a charm - thanks to both of you!

Topic Closed

This topic has been closed to new replies.

About this Topic