Guest User

Untitled

a guest
Nov 19th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. /*
  2. * This code is for WordPress and should be used in functions.php of the active theme.
  3. *
  4. * Before using it, replace "ADVERTISER ID" with your own advertiser ID and "SLOT ID" with your own slot ID
  5. * (you can get both in Google AdSense). For best results, use a reponsive ad unit.
  6. *
  7. * If your posts contain "pre", "noscript" or some other type of HTML block, add them to $block_tags.
  8. *
  9. * You can change the insertion point by changing $after_block.
  10. *
  11. * In English, there are 4.5 letters per word and 150 words per paragraph on average, which is 2025 for 3 paragraphs,
  12. * so a post with 2000 is short and the ad will go to the end of it.
  13. *
  14. * Suggested styling for "ad-conttent-after-p3": 300px width, floated left, on wide displays, and full width, not floated,
  15. * on narrow displays. The ad serving code will deliver ads that fit into the space provided on every device.
  16. */
  17.  
  18. add_filter( 'the_content', 'insert_ad', 999999 );
  19. function insert_ad( $content ) {
  20.  
  21. if ( ! is_single() ) {
  22. return $content;
  23. }
  24.  
  25. $google_ad = '
  26. <p class="ad-content-after-p3">
  27. <ins class="adsbygoogle"
  28. style="display:block"
  29. data-ad-client="ADVERTISER ID"
  30. data-ad-slot="SLOT ID"
  31. data-ad-format="auto">
  32. </ins>
  33. <script>
  34. (adsbygoogle = window.adsbygoogle || []).push({});
  35. </script>
  36. </p>
  37. ';
  38.  
  39. $block_tags = array( 'p' => 1, 'blockquote' => 10, 'table' => 5, 'ul' => 2, 'ol' => 2, 'div' => 3, 'dl' => 2, 'h2' => 2, 'h3' => 2, 'h4' => 2 );
  40. $after_block = 3;
  41. $start = 0;
  42. for ( $block = 0; $block < $after_block; $block++ ) {
  43. $start = stripos( $content, '<', $start ); // Find the start of the next block
  44. $closing_tag = '</p>'; // Fallback
  45. foreach ( $block_tags as $tag => $length ) {
  46. if ( strtolower( substr( $content, $start+1, $length ) ) == $tag ) {
  47. $closing_tag = "</$tag>";
  48. break;
  49. }
  50. }
  51. $end = stripos( $content, $closing_tag, $start );
  52. if ( $end !== false ) {
  53. $end += strlen( $closing_tag );
  54. $start = $end + 1;
  55. }
  56. }
  57.  
  58. if ( $start < 2000 ) { // Nothing found or content too short - show ad after content
  59. return $content . $google_ad;
  60. }
  61.  
  62. // Insert ad after 3rd block
  63. return substr( $content, 0, $start-1 ) . $google_ad . substr( $content, $start );
  64. }
Add Comment
Please, Sign In to add comment