Question

I'm queueing several scripts in my themes Functions.php:

if ( ! function_exists('b99_init_scripts') ) :
    function b99_init_scripts(){

        if ( !is_admin()){
            wp_deregister_script('jquery');
            wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, null, false);
            wp_enqueue_script('jquery');

        wp_register_script('B99', get_template_directory_uri().'/javascript/site/B99.js', array('jquery'), null, false);
            wp_enqueue_script('B99');

        wp_register_script('B99-Nav', get_template_directory_uri().'/javascript/site/module/B99.Navigation.js', array('B99'), null, false );
        wp_enqueue_script('B99-Nav');

            if ( is_page('portfolio') || is_front_page() ){
                wp_register_script('B99-Portfolio', get_template_directory_uri().'/javascript/site/module/B99.Portfolio.js', array('B99-Nav'), null, false);
                wp_enqueue_script('B99-Portfolio');
            } // fails if add_action is set to 'init'

            if ( is_singular() && get_option( 'thread_comments' ) ){
                wp_enqueue_script( 'comment-reply' );
            }
        }
    }
    endif;
    add_action( 'wp_enqueue_scripts', 'b99_init_scripts' );

I have read that the proper place to add_action is to 'init'

add_action( 'init', 'b99_init_scripts' );

However, my is_page('xxx') checks all fail during init.

Coded as I have pasted above:

add_action( 'wp_enqueue_script', 'b99_init_scripts' );

works as expected and the page checks work normally, but I don't think I should be deregistering, registering, and enqueueing during the wp_enqueue_scripts routine.

Is there a better location to hook into, or can I alter my page check during init to function correctly (I assume the page check doesn't work because the needed queries haven't fired yet).

Was it helpful?

Solution

I would suggest creating a function named b99_register_scripts() and hook this into init. Then you can create another function named b99_enqueue_scripts() and hook it into wp_print_scripts.

OTHER TIPS

wp_enqueue_scripts is fine if it works for you. or wp_print_scripts is also an option.

the point of wp_register_script is so you can register something anywhere in your code if you have multiple potential dependencies, and then just enqueue once in the proper location. if you're doing it all in one place you can just skip registering it and just enqueue it straight away, the results will be the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top