[Resolved] insert shortcode in all post

Home Forums Support insert shortcode in all post

  • This topic has 3 replies, 2 voices, and was last updated 2 months ago by Leo.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1372358
    Arnab Mohapatra

    Hi,

    I want to insert [TOC]in every post automatically after the first paragraph in posts. Is it something that can be done?

    Thank you.

    #1372429
    Leo
    Staff
    Customer Support

    Hi there,

    Unfortunately there is no hook after the first (or any) paragraph.

    You will need to add it manually to every post.

    #1377853
    Arnab Mohapatra

    Thanks leo,

    Got it done on my own.

    Here is the code for future reference.

    add_filter( 'the_content', 'prefix_insert_post_shortcode' );
    function prefix_insert_post_shortcode( $content ) {
    	$short_code = 'YOUR SHORTCODE GOES HERE';
    	if ( is_single() && ! is_admin() ) {
    		return prefix_insert_after_paragraph( $short_code, 1, $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 );
    }
    #1377958
    Leo
    Staff
    Customer Support

    Glad to hear 🙂

    Thanks for sharing!

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