I have a with an id of "ad". I am trying to put in an adsense ad in there using JavaScript when a user meets a condition. Basically when a user meets a certain condition, ads will be shown.
This is my code:
if ($resultTot = $db->query($queryTot))
{
$data = $resultTot->fetch_assoc();
if($data["total"]>1)
{
echo "<script>
document.getElementById('ad').innerHTML = 'async src='//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'
<!-- YC2 ads -->
<ins class='adsbygoogle'
style='display:block'
data-ad-client='ca-pub-4557496244647182'
data-ad-slot='4151529047'
data-ad-format='auto'></ins>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>";
}
}
When I use document.getElementId() to change let's say a p tag, it works. I just can't get the adsense to display. Any ideas on how I can add it in there and why my code isn't working?
You just need to print regular AdSense JS code. No need to get any elements with JS.
Currently you are just editing contents of #ad DOM element. This dosen't work, because it has to be <script> and not inside of it. src is attribute.
It must end up like this
<script async src='//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'></script>
So, use this:
if ($resultTot = $db->query($queryTot))
{
$data = $resultTot->fetch_assoc();
if($data["total"]>1)
{
echo "
<div id='ad'>
<!-- YC2 ads -->
<ins class='adsbygoogle'
style='display:block'
data-ad-client='ca-pub-4557496244647182'
data-ad-slot='4151529047'
data-ad-format='auto'></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<script>
var script = document.createElement('script');
script.async = true;
script.src = '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
document.getElementById('ad').appendChild(script);
</script>
";
}
}
Related
I added a Cookies Consent banner. The requirement is that https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js loaded before any other script. I now wonder if appendChild is the right choice. Will it load OtAutoBlock at the exact position I wrote it or will it append the script to the end of the tag (which would be too late). It has to be the first script that's loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- OneTrust Cookies Consent Notice -->
<script type="text/javascript">
if ("%REACT_APP_COOKIE_BAR%" === "true") {
var otAutoBlock = document.createElement("script");
otAutoBlock.setAttribute("type", "text/javascript");
otAutoBlock.setAttribute("src", "https://cdn.cookielaw.org/consent/c4337328/OtAutoBlock.js");
var otSDKStub = document.createElement("script");
otSDKStub.setAttribute("type", "text/javascript");
otSDKStub.setAttribute("src", "https://cdn.cookielaw.org/scripttemplates/otSDKStub.js");
otSDKStub.setAttribute("charset", "UTF-8");
otSDKStub.setAttribute("data-domain-script", "c4337328");
document.getElementsByTagName("head")[0].appendChild(otAutoBlock);
document.getElementsByTagName("head")[0].appendChild(otSDKStub);
function OptanonWrapper() { }
}
</script>
<script type="text/javascript">
/* [Should load after OtAutoBlock loads to avoid tracking before consent was given] */
</script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
document.head.appendChild(script) will add it to the end of the <head> tag, so it will load after all other scripts. You can do two things:
You load it with appendChild at the end, and have all your other scripts with a defer attribute, like this: <script defer> /* something */ </script> The defer forces a script to execute after the page is loaded, but if you load the OtAutoBlock without a defer, it will run before the others. The only thing to note is that defer will cause the scripts not to run last, but after the entire page loads, which includes CSS stylesheets, other JavaScripts, icons, images, HTML content, XHR requests in <script> tags, etc.
<script>
const load = true; // your stuff here
if (load)
{
const script = document.createElement('script');
window.hasRunned = false;
script.text = 'alert(\'OtAutoBlock running.\'); window.hasRunned = true;';
document.head.appendChild(script);
}
</script>
<script defer>
alert('Another script. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
<script defer>
alert('And yet another. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
You use insertBefore to add it before the other scripts, so it will run before them. No need to use defer with this method. This might be what you want if you need the scripts to run before the page loads.
<script>
const load = true; // your stuff here
if (load)
{
let script = document.createElement('script');
window.hasRunned = false;
script.text = 'alert(\'OtAutoBlock running.\'); window.hasRunned = true;';
document.head.insertBefore(script, document.head.children[0]);
}
</script>
<script>
alert('Another script. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
<script>
alert('And yet another. Has runned OtAutoBlock: ' + window.hasRunned);
</script>
I would like to find a number of div classes and add a code after class two.
UPDATE
It works just as it should when writing another code instead of Google ad codes.
<script>
$(function()
{
var say = $('.panel-footer.clearfix').length;
if(say >= 3){
$('.panel-footer.clearfix')[1].after('<script async
src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:100px"
data-ad-client="ca-pub-3767785488130692"
data-ad-slot="3213073317"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>');
}
});
but it doesn't work. The code is running at the bottom of the page instead of the number two div.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel-footer clearfix"></div>
<div class="panel-footer clearfix"></div>
<div class="panel-footer clearfix"></div>
<script>
function insert_adsbygoogle(arg1) {
//https://support.google.com/adsense/answer/7477845?hl=en
(window.adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-3767785488130692",
data_ad_slot: "3213073317",
enable_page_level_ads: true
});
var say = $('.panel-footer.clearfix').length;
if (say >= 3) {
$('.panel-footer.clearfix').eq(1).after("<div id=write_container_for_adsbygoogle></div>");
// container is where you want the ad to be inserted
var script = document.createElement("script");
script.type = "text/javascript";
script.setAttribute("async", "");
script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
$('#write_container_for_adsbygoogle').after(script);
} else if (arg1 === "first") {
$(window).on("load", insert_adsbygoogle);
}
}
insert_adsbygoogle("first");
</script>
Aussuming that clearfix is class name
<script>
$(function()
{
var say = $('.panel-footer.clearfix').length();
if(say >= 3){
$('.panel-footer.clearfix:eq(2)').after('<?php echo
get_option("my_php_code");?>');
}
});
</script>
You can achieve this by using the indexation of the array returned by jquery, also length is not a function so it's just length.
$(function()
{
var say = $('.panel-footer clearfix').length;
if(say >= 3){
$('.panel-footer clearfix')[1].after('<?php echo get_option("my_php_code");?>');
}
});
If clearfix is a class you must use: $('.panel-footer.clearfix') as remarked in another comment.
I am trying to insert Author meta i.e Google adsense Publisher ID and Adunit slot number in functions.php for wordpress. The code am using displays this metas as text e.g xxxxxxxxxxxxxxxxxxx i.e both the ID and slot number in same line on the web page and does not show the google adsense script/ad unit.
CODE
//RECTANGLE Adsense UNit
function get_rectangle() {
global $post; $author_id=$post->post_author;
if(is_single()) {
$rec_Ad.= '<div>';
$rec_Ad.= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 300x250 -->
<ins class="adsbygoogle"
style="display:inline-block;width:300px;height:250px"';
if (get_the_author_meta('rectangle', $author_id)) {
$rec_Ad.= 'data-ad-client="ca-pub-'.the_author_meta('pub-id', $author_id).'"';
$rec_Ad.= 'data-ad-slot="'.the_author_meta('rectangle', $author_id).'"></ins>';
} else {
$rec_Ad.= 'data-ad-client="ca-pub-xxxxxxxxxxxxxxx"';
$rec_Ad.= 'data-ad-slot="xxxxxxxxxxxxxxxxxx"></ins>';
}
$rec_Ad.= '<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>';
}
return $rec_Ad;
}
MAIN FOCUS
$rec_Ad.= 'data-ad-client="ca-pub-'.the_author_meta('pub-id', $author_id).'"';
$rec_Ad.= 'data-ad-slot="'.the_author_meta('rectangle', $author_id).'"></ins>';
The code is supposed to display in single.php page, the ad unit of author if it exists else show the default ad unit.
THe solution can be found in the link below.
How Can I return adsense code from a function in wordpress
credit to #Quack.
Change
$rec_Ad.= 'data-ad-client="ca-pub-'.the_author_meta('pub-id', $author_id).'"';
$rec_Ad.= 'data-ad-slot="'.the_author_meta('rectangle', $author_id).'"></ins>';
to
$rec_Ad .= 'data-ad-client="ca-pub-'. get_the_author_meta('pub-id', $author_id) .'"';
$rec_Ad .= 'data-ad-slot="'. get_the_author_meta('rectangle', $author_id) .'"></ins>';
}
USE get_the_author_meta and NOT the_author_meta
I have a code that i want to execute but dont know how to go about it. I have a page that you can convert between two languages, english and french. I want to run a script in my index.html.erb file only if the page is in french and not in English.
This code is at the beginning of my index.html.erb file.
<script>
var a = <%= params[:locale]%>
if(a == "fr")
{
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 1001007867;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
</div>
</noscript>
}
</script>
I am not sure if my code is correct. Any help is appreciated.
you cant nest script tags, you could append a script tag if your condition is met, sth. like :
<script>
var a = <%= params[:locale]%>;
console.log(a) /* THIS REALLY LOGS THE EXPECTED VALUE ? */
if(a == "fr")
{
var google_conversion_id = 1001007867;
var bh = document.createElement('script'), s = document.getElementsByTagName('script')[0];
bh.type = 'text/javascript';
bh.src = '//www.googleadservices.com/pagead/conversion.js';
s.parentNode.insertBefore(bh, s);
}
</script>
<noscript>
<div style="display:inline;">
</div>
</noscript>
the better solutions would be if your templating-language e.g <%= %> supports if else conditions
check your browser console for errors
I am setting cookie in Jquery according to screen width . Like this
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).on('pageinit','#outerPage',function(){
var windowWidth = $(this).width();
// alert(windowWidth);
if(windowWidth <290)
{
console.log('cookie:small');
$.cookie("adds", 0);
//setTestCookie("adds","0");
}
else
{
console.log('cookie :Big');
$.cookie("adds", 1);
//0setTestCookie("adds","1");
}
});
</script>
And then I am using these cookie to validate a div in php along with some other parameter in the same file like this
<?php
if($current_item == 2 && $_COOKIE['adds'] == '1')
{
//place the adsense after the third ad.
?>
<div id="bloque" class="addsTpl addBigphone" style="min-height:90px">
<div class="google_add">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- resultmobile -->
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:90px"
data-ad-client="ca-pub-765756"
data-ad-slot="657567"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
</div
<?php
}
?>
So far so good .The problem I am facing is that the if() statement is only getting true after I reload the page .
What I have understood is that the cookie is set after the server if() statement is executed in the first time as the Jquery will execute only after the server script is done loading .
Can any one suggest me any other method I can use to do this .
Thanks & regards
thats correct, the server side code is running first and serving up you page which only then executes the javascript - which is too late for you
You could move the window size test that you run to set the cookie into an earlier page in your app (e.g. a login page) or you could have a 'hidden' page which runs your javascript and then immediately redirects to your main page e.g.
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).on('pageinit','#outerPage',function(){
var windowWidth = $(this).width();
// alert(windowWidth);
if(windowWidth <290)
{
console.log('cookie:small');
$.cookie("adds", 0);
//setTestCookie("adds","0");
}
else
{
console.log('cookie :Big');
$.cookie("adds", 1);
//0setTestCookie("adds","1");
}
// redirect to the actual page you want
document.location.href = 'new main page url'
});
</script>
So your hidden page is never rendered - it just runs the javascript and then redirects to the main page.
Hope that helps
Garrett