Site logo

[Support request] How To Insert Text or Image After 5 Paragraphs For Specific Category’s Post

Home Forums Support [Support request] How To Insert Text or Image After 5 Paragraphs For Specific Category’s Post

Home Forums Support How To Insert Text or Image After 5 Paragraphs For Specific Category’s Post

  • This topic has 3 replies, 2 voices, and was last updated 4 years ago by David.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2220063
    Md.

    Hi,

    I want to insert specific text or image after 5 paragraphs for a specific category’s post. How can I do it using the GP Premium Elements Hook?

    Post Example: https://boipdf.com/11-12-sociology-1st-paper-guide/

    Where I want to add specif text or image: https://postimg.cc/dk3zhw0X

    #2220084
    David
    Staff
    Customer Support

    Hi there,

    To do that means you have to filter the_content of the post.
    And the best method is to use the Ad Inserter plugin:

    https://wordpress.org/plugins/ad-inserter/

    And in this reply i show how you can select where to insert your content:

    https://generatepress.com/forums/topic/ad-placement-2/#post-2169661

    #2220393
    Md.

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

    #2220407
    David
    Staff
    Customer Support

    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.

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.