With enqueue you would change $deps to your script or array of scripts that are needed to run first for your script to work.

<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>

For example:

function script_that_requires_jquery() {
    wp_register_script( 'script-with-dependency', 'http://www.example.com/script-with-dependency.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'script-with-dependency' );
}
add_action( 'wp_enqueue_scripts', 'script_that_requires_jquery' );

I usually do this but it doesn’t always seem to work:

function script_that_requires_jquery(){
    if ( wp_script_is( 'jquery', 'done' ) ) { ?>
        <script type="text/javascript">
        (function($) {
            // jquery function goes here    
        })( jQuery );
        </script>
    <?php }
}
add_action('wp_footer', 'script_that_requires_jquery');

Maybe this is it?

function script_that_requires_jquery(){
    wp_enqueue_script( 'jquery' );
    ?>
        <script type="text/javascript">
        (function($) {
            // jquery function goes here    
        })( jQuery );
        </script>
    <?php 
}
add_action('wp_footer', 'script_that_requires_jquery');

2 s
2

function script_that_requires_jquery() {
    wp_register_script( 'script-with-dependency', 'http://www.example.com/script-with-dependency.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'script-with-dependency' );
}
add_action( 'wp_enqueue_scripts', 'script_that_requires_jquery' );

This is the correct method to enqueue scripts (and styles for that matter). You should always be using wp_enqueue_scripts to hook scripts and styles to.

There are a few thing here to check when you register scripts and styles. Firstly, make sure that the order you are placing them inside your function in is correct. The first script in the function will run first, the second second etc.. So, you cannot place your jquery dependant script before jquery, it will not work

The other potential pitfall here is add_action( $hook, $function_to_add, $priority, $accepted_args );. Without setting the $priority parameter, there is always the danger that your script/style will be loaded before other scripts/styles that might overwrite yours.

In your case, your script might be loaded before jquery, so it will not work. I always set this parameter with a very low priority (very high number) when I add custom scripts and styles. This ensures that my scripts and styles loads dead last. So I will do something like this

add_action( 'wp_enqueue_scripts', 'script_that_requires_jquery', 999 );

Leave a Reply

Your email address will not be published. Required fields are marked *