I have a function, within functions.php
(all code below), that adds an advertisement after x
amount of paragraphs to any given single.php
post. I have a custom-post-type called advertising
that has a Title, Image, and URL field for the advertisement post. In any single.php
post I have a checkbox to show the ad (true / false) and a number field for the author to choose how many paragraphs to skip before inserting the image advertisement.
UPDATED CODE: code below works, however I am unable to get a random post. It keeps pulling the absolute latest post without rotating to the other ones.
// http parser
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
// filter content with ad
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
// checkbox to show ad, default true
if ( get_field('show_advertisement') ) {
if ( is_single() && ! is_admin() ) {
// get post-type
$random_ad = get_posts(array(
'numberposts' => 1,
'post_type' => 'advertising',
'order' => 'rand',
'posts_per_page'=>'1'
));
// get post-type fields
$random_ad = array_shift($random_ad);
$link = addhttp( get_field('advertisement_link', $random_ad->ID));
$image = get_field('upload_advertisement', $random_ad->ID);
// get html
$ad_code = '<a href="'.$link.'" target="_blank"><img src="'.$image.'" /></a>';
// show ad after # paragraphs
$show_after = get_field('advertisement_show_after');
// return appended $content
return prefix_insert_after_paragraph( $ad_code, $show_after, $content );
} else {
// do nothing
}
} else {
return $content;
}
}
// insert ad into post
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
EDIT: SOLVED! Changed order
to orderby
and the above code works.
WP_Query
doesn't work, but I don't see where you've tried to use it.WP_Query
into something usable like$ad_code
. It's getting a bit over my head at this point.