[Resolved] Show Element after specific paragraph

Home Forums Support [Resolved] Show Element after specific paragraph

Home Forums Support Show Element after specific paragraph

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2067936
    Swadhin

    Hi David & Team,

    I want to show an ad after a specific number of paragraphs of content. GP hooks currently allows ads/custom element after_entry_header as the only place to show an ad inside the blog post.

    I saw this tutorial in the forum that shows how to create a hook for showing ad after the first paragraph. Which is awesome!

    Now, I want to ask:

    1) Can we create a hook that activates (shows ad) after the reader has scrolled a certain percentage (say 20%) of the article/page? If yes, please share that code with me!

    2) If no, can you please tell how to change the paragraph number to something of my choice (say para 6) using the above code?

    Thank you,
    -Swadhin

    Thank you,
    -Swadhin

    #2067989
    Ying
    Staff
    Customer Support

    Hi Swadhin,

    That’s a good found.

    Give this a try to add hook after 6th paragraph:

    add_shortcode('portable_hook', function($atts){
    	ob_start();
            $atts = shortcode_atts( array(
                'hook_name' => 'no foo'
            ), $atts, 'portable_hook' );
    		do_action($atts['hook_name']);
    	return ob_get_clean();
    });
    
    add_filter( 'the_content', 'insert_featured_image', 20 );
    function insert_featured_image( $content ) {
        global $post;
        $inserted_hook = do_shortcode('[portable_hook hook_name="after_first_paragraph"]');
        if ( is_single() && ! is_admin() ) {
            return prefix_insert_after_paragraph( $inserted_hook, 6, $content );
        }
        return $content;
    }
    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 );
    }
    #2068382
    Swadhin

    Hi Ying,

    Thank you so much for the code. It worked!

    Best,
    -Swadhin

    Thank you,
    -Swadhin

    #2069083
    Ying
    Staff
    Customer Support

    You are welcome 🙂

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