Insert custom content after nth paragraph of content

Copied
<?php declare( strict_types=1 ); namespace Blockify\Test; use function add_filter; use function explode; use function implode; use function is_singular; add_filter( 'the_content', __NAMESPACE__ . '\\insert_after_second_paragraph' ); /** * Insert custom content after second paragraph of post content. * * @param string $content The content. * * @return string */ function insert_after_second_paragraph( string $content ): string { if ( ! is_singular( [ 'post', 'page' ] ) ) { return $content; } // Change this to the paragraph number you want to insert the content after. $count = 2; // Change this to your own content. $custom_content = '<br/><strong>Custom Content</strong>'; $explode = explode( "</p>", $content ); $explode[ $count ] = $custom_content . $explode[ $count ]; return implode( '</p>', $explode ); }
Code language: HTML, XML (xml)