Include a different advert in each WordPress post depending on category

I’ve had many requestes from people who want to include different adverts on each post according to the post category. One example would be a football website that has a different post category for each team. They might want different ads to show depending on the team. E.g. ads for Liverpool F.C. might not appeal to followers of Manchester United!

With Ad Injection there is no way to achive this directly in the UI, but by adding some simple PHP code to one of the ad slots you can do this.

1. In your plugins directory create a sub-directory called ‘ad-injection-ads’. e.g. /wordpress/wp-content/plugins/ad-injection-ads/

2. Create a text files in this folder for each of the categories that you want an ad for. The text files should be named [category nicename].txt The ‘nicename’ of the category is the category name with spaces and dots converted to ‘-‘ and apostrophes removed. e.g.

Liverpool = liverpool.txt
Manchester United = manchester-united.txt
A.F.C Aldermaston = a-f-c-aldermaston.txt
Bishop’s Stortford = bishops-stortford.txt

ad injection ad code box

3. Then put the code below (from the starting <?php to the closing ?>) into one of the ad box – shown above. The code will load the text file ad matching the category name when the post is displayed.

<?php
$plugin_dir = dirname(__FILE__);
$ad_dir = dirname($plugin_dir).'/ad-injection-ads/';
if (file_exists($ad_dir)){
    global $post;
    $categories = get_the_category($post->ID);
    foreach ($categories as $cat){
        // nicename: spaces and dots are converted to '-' and apostrophes are removed
        $full_ad_path = $ad_dir.$cat->category_nicename.'.txt';
        if (file_exists($full_ad_path)){
            $ad = file_get_contents($full_ad_path);
            if ($ad === false) echo "<!--ADINJ CATCODE: could not read ad from file: $full_ad_path-->n";
            echo $ad;
            break; // only show first category ad that matches
        } else {
            echo "<!--ADINJ CATCODE: could not find ad at: $full_ad_path-->n";
        }
    }
} else {
    echo "<!--ADINJ CATCODE: could not find ad directory: $ad_dir-->n";
}
?>

Some extra information:

  • This code will load one text file ad per post. If for example you had a post with the categories ‘Liverpool’ and ‘Manchester United’ it would load which ever ad it found first.
  • If will ignore categories that have no text file in the directory. If you have a post with the categories ‘Liverpool’ and ‘Latest News’ then it will always load the liverpool.txt as long as you don’t create a ‘latest-news.txt’.
  • This code will only work in ‘direct’ ad insertion mode. It won’t work in ‘mfunc’ mode.

Expansion ideas:

  • Show a default advert if no text file exists.
  • Create multiple text files for each category and then randomly select one (shown below).
  • Use different code for top, random or bottom ads. e.g. you could have liverpool_top.txt and liverpool_random.txt

Randomly picking one advert from a pool of ads

Here is a more complex example which allows each category to have a pool of text ads to choose from. It will randomly pick a file that contains the category nicename as a substring. If the category nicename is ‘liverpool’ the code will pick out any files in the directory containing ‘liverpool’, e.g. ‘liverpool.txt’, ‘liverpool1.txt’, ‘liverpool2.txt’. If you put this code into the ‘random’ advert and want a different advert to appear in each slot you should tick the ‘Re-select an ad for each position on post’ box in the ad placement settings of Ad Injection.

<?php
$adinj_filter_category_ads_filter;
if (!function_exists('adinj_filter_category_ads')){

function adinj_filter_category_ads($file) {
    global $adinj_filter_category_ads_filter;
    return strpos($file, $adinj_filter_category_ads_filter) !== false; 

}}
$plugin_dir = dirname(__FILE__);
$ad_dir = dirname($plugin_dir).'/ad-injection-ads/';

if (file_exists($ad_dir)){
    $files = scandir($ad_dir);
    global $post;
    $categories = get_the_category($post->ID);
    foreach ($categories as $cat){

        // nicename: spaces and dots are converted to '-' and apostrophes removed
        global $adinj_filter_category_ads_filter;
        $adinj_filter_category_ads_filter = $cat->category_nicename;
        $filtered_files = array_filter($files, 'adinj_filter_category_ads');
        $random_file = array_rand($filtered_files);
        $full_ad_path = $ad_dir.$filtered_files[$random_file];
        if (file_exists($full_ad_path)){

            $ad = file_get_contents($full_ad_path);
            if ($ad === false){

                echo "<!--ADINJ CATCODE: could not read ad at: $full_ad_path-->n";
            }
            echo $ad;
            break; // only show first category ad that matches
        } else {

            echo "<!--ADINJ CATCODE: could not find ad at: $full_ad_path-->n";
        }
    }
} else {

    echo "<!--ADINJ CATCODE: could not find ad directory: $ad_dir-->n";
}
?>

Randomly picking many adverts from a pool of ads

This will pick a selection of adverts from an ad pool and display them all without duplicates. The use case for this could be if you want to display a selection of adverts down your sidebar. You might have a pool of 20 adverts, and this code can pick any number of those and show them in random positions, without duplicating any adverts. Name your adverts ‘widgetadpool1.txt’, ‘widgetadpool2.txt’, etc. Then modify the ‘$i < condition' in the for loop to select how many of the adverts you want to show.

<?php
if (!function_exists('adinj_adhtml_filter_ads')){

function adinj_adhtml_filter_ads($file) {
    return strpos($file, 'widgetadpool') !== false; 

}}
$plugin_dir = dirname(__FILE__);
$ad_dir = dirname($plugin_dir).'/ad-injection-ads/';

if (file_exists($ad_dir)){
    $files = scandir($ad_dir);
    $filtered_files = array_filter($files, 'adinj_adhtml_filter_ads');
    for ($i=0; $i<10; ++$i){ // max num ads shown
        $random_file = array_rand($filtered_files);
        $full_ad_path = $ad_dir.$filtered_files[$random_file];
        if (file_exists($full_ad_path)){

            $ad = file_get_contents($full_ad_path);
            if ($ad === false){

                echo "<!--ADINJ RAND: could not read ad at: $full_ad_path-->n";
            }
            echo $ad.'<br />';
        } else {

            echo "<!--ADINJ RAND: could not find ad at: $full_ad_path-->n";
        }
        unset($filtered_files[$random_file]);
        if (empty($filtered_files)) break;
    }

} else {
    echo "<!--ADINJ RAND: could not find ad directory: $ad_dir-->n";
}
?>

3 Comments on “Include a different advert in each WordPress post depending on category”

  1. Hello, I’m fairly php stupid. I want to show ad1 at the top of the post in category1 and ad2 and the bottom of the post in category1. In other words, 2 ads per post based on the category at different places in the post.

    I’ve created 2 txt files: birds_top.txt and birds_bottom.txt as mentioned in the example above. I’ve put the php code into the ad box, but nothing shows up. If I only do a single ad on the page, using a text file birds.txt, the ad shows up. It’s when I try to expand to 2 ads per page per category, things don’t show up.

    I’m presuming that there needs to be a modification to the php code that I put in the ad box, but that’s where the php stupid comes in.

    Could you please help?

    Thanks!

  2. Wait, I figured it out! For others who need to know how to do it, you need to change this part here:

    category_nicename.’.txt’;

    to:

    category_nicename.’_bottom.txt’; or category_nicename.’_top.txt’;

    I hope that helps someone!

Leave a Reply

Your email address will not be published. Required fields are marked *

Do NOT fill this !