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

I was wondering if we can set the order of a function hooked to wp_footer(), I created a function that echos:

<script> ajsfunction(); </script>

and I also enqueued the js file of this function and printed it in the footer but the above is being printed before linking to the js file so it’s not working, I’m doing this because this script is not run on all pages only on specific ones.

Read More

if we can’t do this with wp_footer is there a way to output this script tag after the enqueued js file ?

thanks in advance.

Related posts

Leave a Reply

2 comments

  1. 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).