I'm having issues enqueueing a script in the header. I'm working on a Wordpress site where the page content is loaded via AJAX. To do this I have to enqueue the script with the AJAX call. I do this using the following code:

function ajax_enqueue_scripts() {
  $dir = plugins_url().'/product-types';
  global $post;
  if ( 'product' === $post->post_type ) {    
    wp_enqueue_script( 'ajax-products', $dir. '/js/ajax.js', __FILE__, array('jquery'), '1.2',false );
    wp_localize_script( 'ajax-products', 'ajaxfunction', array('ajax_url' => admin_url( 'admin-ajax.php' )));

add_action( 'wp_enqueue_scripts', 'ajax_enqueue_scripts' );

The problem is that it keeps loading the JS file in the footer. Is there something I'm missing?


You just have your arguments lined up wrong. Change the line to

wp_enqueue_script( 'ajax-products', plugins_url( '/js/ajax.js', __FILE__ ), array('jquery'), '1.2', false );

You can use plugins_url() with the second parameter of __FILE__ to get the directory of the specific pluign, and in the first argument you pass the relative location of your script.

The rest is pretty straight forward - dependencies, version and $in_footer. As you passed one more arguments, I suppose WordPress thought your version (fifth argument) is true, as you passed '1.2'. But I am not sure about that.

  • Also, if jQuery is set to be loaded in footer, this script will be loaded in footer as well after jQuery, just because it depends on jQuery, no matter what parameters you set in wp_enqueue_script(). – cybmeta Feb 1 '16 at 11:19
  • It worked! What an oversight. Thanks for the help! – Lody Aeckerlin Feb 1 '16 at 11:25

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.