so I am working on a custom theme in WordPress. I used to have a whole lot of JS in the head.php, like this:
jQuery(document).ready(function($) {
$('.widgetblock').accordion({
//args
});
if ( have_posts() ) {
//stuff
}
});
However I’ve since read that the proper way to add JS in WordPress is to use wp_enqueue_script()
in functions.php, so I’m trying to do that. What I’ve done is just put that same code into a .js file that I’ve save in the corresponding folder, and I’m then loading it like this:
function script_assets() {
wp_enqueue_script( 'js-code', get_template_directory_uri() . '/js/js-code.js', array( 'jquery', 'jquery-ui-widget' ) );
}
add_action( 'wp_enqueue_scripts', 'script_assets' );
I’ve added JQuery and JQuery UI as dependencies.
However, that doesn’t work. Chrome says that accordion() and have_posts() aren’t defined. I also encounter issues if I try to reference specific elements from my CSS.
So, what am I to do? This is probably a very basic problem, but I can’t find how to solve it.
Another problem is, how do I make 100% sure that some JS scripts are loaded after the CSS? I’m using -prefix-free which should be loaded right after it, but I’m not sure that’s possible with wp_enqueue…
EDIT: I can’t really load that script in the footer, it needs to be loaded immediately after the CSS. :/
Thanks.
Every time I have had to add jQuery to a WordPress site I use this code that I found on CSS-tricks
For what I understand, once you load jQuery this way you prevent conflicts and it gets loaded only once.
Well someone else posted an answer but then deleted it so…
The dependency I was using here
wp_enqueue_script( 'js-code', get_template_directory_uri() . '/js/js-code.js', array( 'jquery', 'jquery-ui-widget' ) );
was wrong; I should have used jquery-ui-accordion, which jquery-ui-widget doesn’t include. I elected to include the whole of jquery-ui (so I could use other features without having to add specific dependencies for each of them) but to do that I had to link to Google’s, since there is no full package in WP.That fixed some of my issues, not everything (the -prefix-free script still isn’t loaded right after the stylesheet, and I have to find a way to replace the PHP functions that I used before) but the website’s working, so there’s that 🙂
Thanks to whomever actually answered, I don’t remember your username, sorry.