Advertisement
Guest User

Untitled

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