I'm looking to add jQuery function to the head of specific pages on WordPress. It's to allow accordions to be closed after being opened.
I only require to use it on -> WooCommerce Single Product pages, FAQ page and Contact us page.
- Page Slugs = ('faqs','contact')
- is_singular('product') for Single Product Page
Action added to functions.php
- It saves successfully but doesn't work. Not sure what I've done wrong.
function my_closeaccordionscript() {
if( is_page( array( 'faqs','contact') ) ){
wp_enqueue_script( 'toggle-script', '/assets/js/accordiontoggle.js', array(), '1.0.0', true );
}
if(is_singular('product')){
wp_enqueue_script( 'toggle-script', '/assets/js/accordiontoggle.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_closeaccordionscript' );
This is the file content of 'accordiontoggle.js
' which is saved in child theme directory... wp-content/themes/child-theme/assets/js/accordiontoggle.js
EDIT:
The answer was to use get_theme_file_uri()
{wp_enqueue_script( 'script-name', get_theme_file_uri('/assets/js/accordiontoggle.js'), array(jquery), '1.0.0', true );}
CodePudding user response:
Your PHP code is correct for selectively loading the script, and the use of two IF statements is proper control flow.
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.'
CodePudding user response:
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 );}