I’ve been doing some affiliate marketing on one of the sites I manage which required some ad code to be inserted mid-post

I also needed to be able to insert this ad code on a specific tree or branch of pages, e.g. sub-pages and their immediate parent (ancestors). Luckily CSS Tricks has a useful function to work this out which can be reused elsewhere in your theme.

/*
* Given a page ID, checks to see if were on a page or one of it's childrens.
* https://css-tricks.com/snippets/wordpress/if-page-is-parent-or-child/
*/

function is_tree($pid) {
								
	global $post;
								
	if ( is_page( $pid ) || $post->post_parent == $pid || ($post->ancestors && in_array( $pid, $post->ancestors) ) )
		return true;
	else 
		return false;
};

The next stage was to work out how to actually insert my ad code (using a premium plugin called WP Pro Advertising) in the middle of a post or a page. To do this WPSE gave me the following function

/*
* Inserts ad code after 'x' paragraphs in the_content
* http://wordpress.stackexchange.com/questions/58605/insert-ad-code-in-the-middle-of-a-post
*/

add_filter('the_content', 'wpse_ad_content');

function wpse_ad_content($content)
{
    if ( !is_tree( 76 ) ) return $content;

    $paragraphAfter = 6;
    $content = explode("</p>", $content);
    $new_content = '';
    for ($i = 0; $i < count($content); $i++) {

	if ($i == $paragraphAfter) {
		
		$new_content.= '[pro_ad_display_adzone id="722" align="right" info_text="Advert" info_text_position="above" font_color="undefined" font_size="11" padding="5"]';
        }

        $new_content.= $content[$i] . "</p>";
    }

    return $new_content;
}

 

 

 

Save

Save