0

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

3
  • 1
    How/where are you calling the deregister_about_javascript() function? I understand you've placed the function declaration in the same file but how are you actually calling that function? Commented Dec 1, 2016 at 10:09
  • @Andy I thought about that previously lol and I'm not. The code where I "enqueue" the script works without being called so I figured it must be the same thing. I was wrong? Commented Dec 1, 2016 at 10:12
  • 1
    The first function is called because you've added it to the wp_enqueue_scripts action, so when WordPress fires that action it calls your function. I've posted an answer anyway and it gets rid of the need for a second function. Commented Dec 1, 2016 at 10:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

lol I honestly feel like a complete retard honestly, I didn't call any actions. I like your answer as it makes it more efficient also :) thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.