Enqueue JS and jQuery to head of specific wordpress pages

Solution:1

You need to add jQuery as a dependancy when enqueueing a jQuery script with wp_enqueue_script:

wp_enqueue_script( 'toggle-script', '/assets/js/accordiontoggle.js', array('jquery'), '1.0.0', true );

Typically a jQuery script must be wrapped with:

jQuery(function($) {
    $(document).ready(function() {
    // Your code goes here
    });
 });

Or (use this because you are manipulating images):

jQuery(function($) {
    $(window).on('load', function () {
    // Your code goes here
    });
});

This is important because wp_enqueue_scripts inserts the script into the document <head> which is loaded first. Without waiting for document ready or window load event, you are selecting elements with jQuery that don’t exist yet.

From jQuery docs:

‘A page can’t be manipulated safely until the document is “ready.” jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.’

Solution:2

It could be that it’s located in the child theme. In order to load a script on the frontend that’s located in a child theme folder you can use get_stylesheet_directory_uri(). If the script isn’t located in the header of the file you can you use. add_action('wp_head','my_closeaccordionscript');

function my_closeaccordionscript() { if( is_page( array( 'faqs','contact') ) ){ wp_enqueue_script( 'toggle-script', get_stylesheet_directory_uri() . '/assets/js/accordiontoggle.js', array(), '1.0.0', true ); } if(is_singular('product')){ wp_enqueue_script( 'toggle-script', get_stylesheet_directory_uri() . /assets/js/accordiontoggle.js', array(), '1.0.0', true ); }} add_action( 'wp_enqueue_scripts', 'my_closeaccordionscript' );

Solution:3

Stack member Ruvee provided great assistance with this problem, but his answer / comments seem to have disappeared.

We tried various things, but I finally got it to work by adding get_theme_file_uri()to the file source.

{wp_enqueue_script( 'script-name', get_theme_file_uri('/assets/js/accordiontoggle.js'), array(jquery), '1.0.0', true );}