0

I want to display an image/banner with link, inside the content of the posts of my blog. Neither at the beginning, nor at the end. It should appear somewhere inside the content of the post. I don't want to use a shortcode, I need the banner to be automatically inserted to all posts.

First I created a template part with the banner, which I can easily call using:

<?php get_template_part( 'template-parts/banner' ); ?>

I though that a good rule, would be to insert the banner after say, the 3rd paragraph. Or after 300 words. Or after 900 characters. Or something like that. If the post is too short I don't need the template part to be displayed.

Can anyone please help me achieve this?

2

The main issue I see here is the usage of get_template_part() function in that context. It's not really the best way to go as we're going to filter the content of your posts and you would probably need to get the markup of your banner, not output it immediately. Read more here.

I would suggest to keep the baner markup in a variable or return value of a separate function, like so:

function get_banner_html() {
    return '<div class="baner">Your baner HTML here</div>';
}

Then, you could easily filter the content of all posts with WordPress hook:

function insert_banner_into_content( $content ) {

    // make sure we're affecting only posts
    if ( 'post' !== get_post_type() ) {
        return $content;
    }

    // split content by paragraph tag
    $paragraphs = explode( '<p>', $content );

    // continue only when post has 3 paragraphs or more
    if ( count( $paragraphs ) < 3 ) {
        return $content;
    }
    // add banner after 3rd paragraph
    $paragraphs[2] .= get_banner_html();

    // return modified content
    return implode( '<p>', $paragraphs );
}
// hook it up!
add_filter( 'the_content', 'insert_banner_into_content' );
  • Tested and works! Why do you prefer using return instead of something like this, or both are fine?: if ( 'post' !== get_post_type() ) { $paragraphs = explode( '<p>', $content ); if ( count( $paragraphs ) < 3 ) { $paragraphs[2] .= get_banner_html(); } return implode( '<p>', $paragraphs ); } – IXN Feb 26 '18 at 4:26
  • It's just my preference of coding style, i like to avoid multi level conditionals and else statements to keep my code easy to read. You can turn this logic around, but then you would have to check if the post type IS a 'post', and also you'll need to return the $content untouched otherwise (we are adding the filter to the content, so you should return it anyways). So the code would be structured like this: if ( 'post' === get_post_type() ) { // adding the paragraph logic here } else { return $content; } – Levi Dulstein Mar 7 '18 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.