hyperlink - Open ad clicking anywhere in wordpress -
i have wordpress site , i'm using script
onclick="<?php if(!isset($_cookie['visited'])){echo"window.open('http://link', '_blank')"; setcookie("visited", "1", time()+3600*24); header("refresh:0");} ?>" in body line. means i'm using
<body <?php body_class(); ?> onclick="<?php if(!isset($_cookie['visited'])){echo"window.open('http://link', '_blank')"; setcookie("visited", "1", time()+3600*24); header("refresh:0");} ?>"> on header.php file of theme.
but opens link in every click. want open 1 time until refresh page or open new page. how can it. please help. in advance.
greetings.
like setcookie function reference says:
cookies must sent before output script
first solution
you add @ top oh header.php:
<?php $onclick = ''; if(!isset($_cookie['visited'])) { setcookie('visited', '1', time()+3600*24, cookiepath, cookie_domain); $onclick = 'onclick="window.open(\'http://link\', \'_blank\')"'; } ?> update: i've added constants cookiepath , cookie_domain explained here.
and body tag:
<body <?php body_class(); ?> <?php echo $onclick; ?>> better solution
the prior solution doesn't ensure cookie set before output sent (there characters in 1 of template files before get_header() called, or plugin add something).
instead should add action wordpress hook called before output (like init).
so try adding functions.php file:
add_action('init', 'set_visited_cookie'); function set_visited_cookie() { if (!isset($_cookie['visited'])) { setcookie('visited', '1', strtotime('+1 day'), cookiepath, cookie_domain); } } as body tag:
<body <?php body_class(); ?> <?php if(!isset($_cookie['visited'])): ?> onclick="window.open('http://link', '_blank')" <?php endif; ?>>
Comments
Post a Comment