Advertisement
Guest User

Untitled

a guest
Dec 6th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. <?php
  2. //Insert ads after second paragraph of single post content.
  3. add_filter( 'the_content', 'prefix_insert_post_ads' );
  4. function prefix_insert_post_ads( $content ) {
  5. $ad_code = '<div>Ads code goes here</div>';
  6. if ( is_single() && ! is_admin() ) {
  7. return prefix_insert_after_paragraph( $ad_code, 2, $content );
  8. }
  9. return $content;
  10. }
  11.  
  12. // Parent Function that makes the magic happen
  13. function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
  14. $closing_p = '</p>';
  15. $paragraphs = explode( $closing_p, $content );
  16. foreach ($paragraphs as $index => $paragraph) {
  17.  
  18. if ( trim( $paragraph ) ) {
  19. $paragraphs[$index] .= $closing_p;
  20. }
  21.  
  22. if ( $paragraph_id == $index + 1 ) {
  23. $paragraphs[$index] .= $insertion;
  24. }
  25. }
  26.  
  27. return implode( '', $paragraphs );
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement