Site logo

Archived topic

How To Insert Text or Image After 5 Paragraphs For Specific Category's Post

3 replies · Started by Md. on May 15, 2022

Viewing posts 1–4 of 4

I don't want to use any plugin. How can I do it with only GP Hook?

You cannot do it with a GP Hook, as they are Action Hooks that are baked into the Themes code. And your content is not in the themes code, so there are no action hooks.

You can use a PHP Snippet to filter the_content:

add_filter( 'the_content', 'insert_featured_image', 20 );
function insert_featured_image( $content ) {
    $custom_html = 'your custom content goes here';
    if ( is_single() && in_category('you_category_slug') && ! is_admin() ) {
        return prefix_insert_after_paragraph( $custom_html, 5, $content );
    }
    return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '</p>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {
        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }
        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[$index] .= $insertion;
        }
    }
    return implode( '', $paragraphs );
}

Notes:
a. you will need to add your custom HTML where it says:

$custom_html = 'your custom content goes here';

b. you will need to set the category slug here:

in_category('you_category_slug')

However that is as much as i can offer, and i cannot guarantee it will work as other code on your site may interfere with this. Which is why i suggest you use the ad inserter plugin.

This archived topic is closed to new replies.