Insert After Second Paragraph Without <P> Tag?

I use a code like the one shown below to insert ads after the first paragraph.

The problem is that this code requires the content to be displayed within paragraph tags and I would like to use this code to insert a DIV.
When I simply replace the tags with div tags the code no longer works.

Read More

How do I remove the paragraph tags from the code while allowing the code to remain functional?

<?php
$paragraphAfter= 1; //display after the first paragraph
$content = apply_filters('the_content', get_the_content());
$content = explode("<p>", $content);
for ($i = 0; $i <count($content); $i++ ) {
if ($i == $paragraphAfter) { ?>

CONTENT GOES HERE

<?php }
echo $content[$i] . "</p>";
} ?>

Related posts

2 comments

  1. I need to stress that I think this is going to be very unstable and you may not always get the results you want, but in simple cases this should work.

    $content = apply_filters('the_content', get_the_content());
    $content = explode("</p>", $content, 2);
    // var_dump($content); // debug
    echo $content[0].'</p>';
    echo '<div>Extra Content</div>';
    if (!empty($content[1])) {
      echo $content[1];
    }
    
  2. This one is similar to the one posted above, however there is an extra loop to display all paragraphs after the content.

    <?php $content = wpautop( get_the_content() );
    $content = explode("</p>", $content);
    echo wpautop( $content[0] ).'</p>'; ?>
    
    <p>Special content or page breakpoint</p>
    
    <?php                               
    $i = 0;
    foreach ($content as $paragraph => $value) {
        if ( $i > 0 ) { echo wpautop( $content[$i] ); }
        $i++;
    } ?>
    

    wpautop( get_the_content() ) passes formatted post content to be split through paragraph tags with explode('</p>', $content) and foreach to loop all paragraphs after the fold.

Comments are closed.