-2

I have an external javascript in header section, like this way:

<head>
<script type="text/javascript" src="myscript.js"></script>
</head>

This javascript creates a banner for the cookie law, in every page of the site. The banner is shown only the first time you enter the site.

I want to load this javascript in all site except two page. I use Wordpress and Genesis Framework.

How can I do that?

supap
  • 89
  • 9

2 Answers2

0

Try adding the following PHP within the <head>...</head> of the page template, where the

<script src="bannerscript.js"></script>

would normally go:

<?php

$nobanner = array('page1','page2');
$page = $_SERVER['SCRIPT_NAME'];
$page = str_replace('/', '',$page);

if (!in_array($page,$nobanner)) {
echo '<script src="bannerscript.js"></script>';
}

?>

The script checks the URI, verifies that the page is not one where the banner is not supposed to show and then includes the banner request as normal.

On any of the pages where the banner is not supposed to show - in the example above, that's page1 and page2 - the banner request is never included in the page <head>...</head>.

Rounin
  • 27,134
  • 9
  • 83
  • 108
0

To load your script in a typical Wordpress way, you'll have to check the ID of your current page.

// Main Scripts
function register_banner_js() {

    if (!is_admin()) {
        /* Get id of current page*/
        $page_id     = get_queried_object_id();

        /* Compare the non-relevant page's id with the current page's id, if they don't match, enqueue your banner script*/
        $ids = array(page_id_1, page_id_2);

        if (!in_array($page_id, $ids)){
            wp_register_script('bannerscript', 'path/to/your/bannerscript.js', 'jquery', null, TRUE);
            wp_enqueue_script('bannerscript');
        }
    } 
} 

add_action('wp_enqueue_scripts','register_banner_js')

Put the code in your functions.php. Make sure to check your page's ids and put them in the ids array containing all relevant ids of pages on what your bannerscript shouldn't be loaded.

If you'd like to learn more about Javascript enqueueing check the Wordpress Hook wp_enqueue_script.

Robin Vinzenz
  • 1,247
  • 15
  • 19
  • Hi, Robin, thank you for the tip! This code works very well, but the banner is shown every time the user view a page, not only the first time that he entered the site. Is there a way to avoid that? For the rest, i entered the page ids, and in these page the javascript isn't load, perfect! – supap May 20 '15 at 11:55
  • Ah I'm sorry i didn't notice the "only one time" thing. You could check the Request variable $_Cookie for your given cookie value. http://php.net/manual/en/reserved.variables.request.php – Robin Vinzenz May 20 '15 at 12:05
  • I don't know very well php, you may update the code with this change, please? – supap May 20 '15 at 12:16