I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I've got as far as loading jQuery in functions.php
file, but all of the guides out there are crappy because they assume you already have a ton of WordPress experience. For instance, they say that now that I'm loading jQuery through the functions.php
file, now all I have to do is load my jQuery.
How exactly do I do this? What files, specifically, do I add code to? How exactly do I add it for a single WordPress page?
After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:
Make sure your custom jQuery .js looks like this:
Go to the theme's directory, open up functions.php
Add some code near the top that looks like this:
If you use wordpress child theme for add scripts to your theme, you should change the get_template_directory_uri function to get_stylesheet_directory_uri, for example :
Parent Theme :
Child Theme :
get_template_directory_uri : /your-site/wp-content/themes/parent-theme
get_stylesheet_directory_uri : /your-site/wp-content/themes/child-theme
No. You should never just add a link to an external script like this in WordPress. Enqueuing them through the functions.php file ensures that scripts are loaded in the correct order.
Failure to enqueue them may result in your script not working, although it is written correctly.
you can write your script in another file.And enqueue your file like this suppose your script name is
image-ticker.js
.in the place of
/js/image-ticker.js
you should put your js file path.I know what you mean about the tutorials. Here's how I do it:
First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need
<script>
tags in a .js file).Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:
Notice that I use jQuery and not $ at the start of the function.
Ok, now open your theme's functions.php file. You'll want to use the
wp_enqueue_script()
function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.
WordPress questions can be asked over at WordPress Answers.
Answer from here: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/