1

This code is working in my functions.php and it's loaded properly:

add_action('wp_enqueue_scripts', 'js_custom', 50);
function js_custom() {
    wp_register_script( 'js_custom', get_template_directory_uri() . '/js/custom.js', false, null);
    wp_enqueue_script( 'js_custom' );
}

However, this is not working and not loaded:

if ( is_page(273) ) {
    add_action('wp_enqueue_scripts', 'js_custom', 50);
    function js_custom() {
        wp_register_script( 'js_custom', get_template_directory_uri() . '/js/custom.js', false, null);
        wp_enqueue_script( 'js_custom' );
    }
}

Why it's not loaded? I am on the page with the id equal to 273.

3

I had a similar issue once. I found that running the add_action call outside the conditional worked. So try this:

    function js_custom() {
        if ( is_page(273) ) {
            wp_register_script( 'js_custom', get_template_directory_uri() . '/js/custom.js', false, null);
            wp_enqueue_script( 'js_custom' );
        }
}
add_action('wp_enqueue_scripts', 'js_custom', 50);
5
  • Hmm, I am getting this error: Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'js_custom' not found or invalid function name
    – Derfder
    Dec 15 '13 at 12:10
  • Sorry! Edited answer. The conditional had to go inside the function call. Try it now.
    – JMB
    Dec 15 '13 at 12:15
  • Thanks, now it's working ;). Btw. I would consider this as a bug in WP. Should I post it to the WP team? Or this is not a bug?
    – Derfder
    Dec 15 '13 at 12:26
  • I'm not qualified to say if it's really a bug or not. This is a simple enough fix to wrap the contents of your function in the conditional, that we can continue to do that.
    – JMB
    Dec 15 '13 at 12:59
  • @Derfder It's not a bug but I'll admit the add_action, do_action, add_filter, apply_filter stuff isn't very intuitive when you're getting started with WordPress. Var dump $wp_query in the actual is_page function with the two difference scripts and you'll see the difference. Dec 15 '13 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.