Richard Monjed Richard Monjed - 8 days ago 5
Javascript Question

Condtionally load scripts in wordpress

I can load (enqueue a script in wordpress by using this in my child theme functions.php file:

function my_assets() {

wp_enqueue_script( 'about', get_stylesheet_directory_uri() . '/js/about.js', array( 'jquery' ), '1.0' , true );
}

add_action( 'wp_enqueue_scripts', 'my_assets' );


The loading isn't an issue, the script works, but when I want to conditionally load it up on a page it doesn't work with this code (in the same file and directly below the above code):

function deregister_about_javascript() {
if ( !is_page(490) ) {
wp_dequeue_script( 'about' );
}
}


The script still appears on all pages. I tried using the name of the page, the slug, I changed wp_dequeue_script to admin_dequeue_script and nothing works.

Of note though, when I click on the page to obtain the page ID number whilst in admin, it has the word "post" in the address bar, even though I am in "Pages". wp-admin/post.php?post=490&action=edit

lol It seems so straight forward, what am I missing?

Thank you

Answer

Instead of executing another function to dequeue the script, you could just return early and not enqueue the script in the first place based on a certain condition:

function my_assets() {
    if ( ! is_page( 490 ) ) {
        return;
    }

    wp_enqueue_script( 'about', get_stylesheet_directory_uri() . '/js/about.js', array( 'jquery' ), '1.0', true );
}

add_action( 'wp_enqueue_scripts', 'my_assets' );

Now the wp_enqueue_script function only gets called on page ID 490.