Search code examples
javascriptphpwordpressgenesis

Load a javascript in all site except two page


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?


Solution

  • 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.