Is there a way to set the order of wp_footer hooked functions?

The recommended way is to call your function inside the .js file you are enqueuing. Is there any reason you can’t do that?

If you need access to dynamic data like WP options from within your script, use wp_localize_script to initialize a javascript object with the data you need:

$data = array('some_option' => get_option('an_option_from_my_theme'));

wp_enqueue_script('your_script_handle', 'path/to/the/script.js');
wp_localize_script('your_script_handle', 'my_theme_options', $data);

In your script you can access the data like you would a javascript object:

console.log(my_theme_options.an_option_from_my_theme);


Following your last comment, you have two possibilities:

  1. Put your code inside another javascript file that you enqueue, and make the plugin a dependency of this file.

  2. Add your code within the wp_footer hook, after WP prints footer scripts:

    add_action('wp_footer', function(){
    
     ?>
     <script>
    
     // your javascript
    
     </script>
     <?php 
    
     }, 100);
    

    “100” is the priority, the higher the number – the lower the execution priority of your action. Scripts are printed with the “20” priority

I’d go with (1) if you have a lot of js code, otherwise inline javascript is fine (2).

Leave a Comment