Site logo

Archived topic

insert shortcode in all post

3 replies · Started by Arnab Mohapatra on July 22, 2020

Viewing posts 1–4 of 4

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.

Hi there,

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

You will need to add it manually to every post.

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 );
}

Glad to hear :)

Thanks for sharing!

This archived topic is closed to new replies.