0

I am trying to insert some ad code in a site after X number of elements. The base code I am using was from using

tags (from: http://www.wpbeginner.com/wp-tutorials/how-to-insert-ads-within-your-post-content-in-wordpress/):

function prefix_insert_after_list_item( $insertion, $paragraph_id, $content ) {
  $closing_p = '</p>';
  $paragraphs = explode( $closing_p, $content );
  var_dump($paragraphs);
  foreach ($paragraphs as $index => $paragraph) {

    if ( trim( $paragraph ) ) {
      $paragraphs[$index] .= $closing_p;
    }

    if ( $paragraph_id == $index + 1 ) {
      $paragraphs[$index] .= $insertion;
    }
  }

  return implode( '', $paragraphs );
}

Instead of paragraphs, I am trying to insert them between certain elements. Here is my HTML structure:

<div class="listing">
  <div class="list-item">
  </div>
  <div class="list-item">
  </div>
  <div class="list-item">
  </div>
  <div class="list-item">
  </div>
</div>

I'd like to insert the ads between the list items. Replacing $closing_p = '</p>'; with $closing_p = '<div class="list-item">'; doesn't seem to work though. Is there a way with to target the overall $content element in WordPress, but then target 's within the parent 'listing' ? Or is there another/better way to do what I am trying to do?

0

You should be able to get it to work by changing it to this:

$closing_p = '</div>';

I hope I didn't miss something

  • 1
    The issue is </div> isn't selective enough. There are additional divs in the $content element that I don't want to be selecting. I went ahead and implemented via JS. I decided that was a safer option than trying to manipulate the DOM via PHP like I was trying to do. – Andrew Oct 16 '16 at 1:26

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.