Advertisement in first post


#1

I’m trying to show an advertisement in the first post, only to anonymous users. I’ve tried the following code and everything is in the right place, except that the Javascript that loads the ad doesn’t trigger:

<script type="text/discourse-plugin" version="0.1">

var strVar="";
strVar += "<div align=\"center\" id=\"div-gpt-ad-728x90-ATF\">";
strVar += "    <script data-cfasync=\"false\" type='text\/javascript'>";
strVar += "        freestar.queue.push(function () { googletag.display(\'div-gpt-ad-728x90-ATF\'); });";
strVar += "    <\/script>";
strVar += "<\/div>";

if(Discourse.User.current()== null){
    
     api.decorateCooked($elem => {
    
        counter = 1;
    
        if(counter==1){
            
            firstpost = $elem.html();
            firstpost = $elem.html() + strVar
            
        }
    
        counter++;
    
        console.log(firstpost);
    
    	$elem.html(firstpost);
 
     }, {onlyStream: true});
    
}
   
</script>

I’m hoping there is someone who can guide in the right direction to get the ads fired on the first post!


(Logan Devine) #2

This is what it does Yes I does nothing I do not know the fix


#3

I was able to find the solution. I’m leaving it here for whenever someone else happens to want to do the same and wants to add DFP code in the first post on a thread on Discourse.

Add the code below in the </head> section of the Discourse customizer. Then replace the YOUR_DIV_ID with your own.

<script type="text/discourse-plugin" version="0.1">

var adDiv="";
adDiv += "<div align=\"center\" id=\"YOUR_DIV_ID\">";
adDiv += "<\/div>";   

if(Discourse.User.current()== null){  // if null, the user is not logged in

    api.addPostTransformCallback((t)=>{   

        if (t.post_number === 1) {  // check if we're in post #1
        
            t.cooked = t.cooked + adDiv;        // append our advertising div
            googletag.queue.push(function () { googletag.display('YOUR_DIV_ID'); }); // fill div with ad
         
        }   
    });
 }    
</script>

If you use it, I would love to hear from you, especially on which forum and how it performs!