1

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.

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>";
} ?>
2
  • You are trying to insert a <div> inside a <p> tag?
    – s_ha_dum
    Jun 24 '13 at 15:07
  • I would like to insert a specific div into a post after the first paragraph. Jun 24 '13 at 15:21
3

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
  • Thanks for the help, I'll wait for a more stable solution before I choose the best answer. Jun 24 '13 at 15:34
  • I am not sure there is a more stable solution. It depends on the markup in your post. I am almost certain there is a way to break this with carefully constructed (broken) markup.
    – s_ha_dum
    Jun 24 '13 at 15:36
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.