Advertisement
Guest User

Untitled

a guest
Feb 24th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. add_filter( 'the_content', 'prefix_insert_post_ads' );
  2. function prefix_insert_post_ads( $content ) {
  3.  
  4. // checkbox to show advertisement on post, default true
  5. if ( get_field('show_advertisement') ) {
  6.  
  7. // should be where I pull the custom-post-type
  8. // $ad_code = '<a href="'.$link.'" target="_blank"><img src="'.get_field('upload_advertisement').'" /></a>';
  9. //
  10. $random_ad = get_posts(array(
  11. 'numberposts' => 1,
  12. 'post_type' => 'advertising',
  13. 'order' => 'rand'
  14. ));
  15.  
  16. if (!empty($random_ad)) {
  17. $random_ad = array_shift($random_ad);
  18. $link = addhttp( get_field('advertisement_link', $random_ad->ID));
  19. $image = get_field('upload_advertisement', $random_ad->ID);
  20. }
  21.  
  22. if ( is_single() && ! is_admin() ) {
  23.  
  24. // field on single.php post for how many paragraphs to post the ad after
  25. $show_after = get_field('advertisement_show_after');
  26.  
  27. // return the $ad_code, show ad after # paragraphs, get content
  28. return prefix_insert_after_paragraph( $random_ad, $show_after, $content );
  29. }
  30.  
  31. return $content;
  32.  
  33. } else {
  34.  
  35. return $content;
  36.  
  37. }
  38. }
  39.  
  40. // Parent Function that makes the magic happen
  41. function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
  42. $closing_p = '</p>';
  43. $paragraphs = explode( $closing_p, $content );
  44. foreach ($paragraphs as $index => $paragraph) {
  45.  
  46. if ( trim( $paragraph ) ) {
  47. $paragraphs[$index] .= $closing_p;
  48. }
  49.  
  50. if ( $paragraph_id == $index + 1 ) {
  51. $paragraphs[$index] .= $insertion;
  52. }
  53. }
  54.  
  55. return implode( '', $paragraphs );
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement