wordpress use jquery in functions php

Solutions on MaxInterview for wordpress use jquery in functions php by the best coders in the world

showing results for - "wordpress use jquery in functions php"
Luigi
03 Jan 2021
1I know what you mean about the tutorials. Here's how I do it:
2
3First 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).
4
5Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:
6
7jQuery(document).ready(function($) {
8  $('#nav a').last().addClass('last');
9})
10Notice that I use jQuery and not $ at the start of the function.
11
12Ok, 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:
13
14add_action( 'wp_enqueue_scripts', 'add_my_script' );
15function add_my_script() {
16    wp_enqueue_script(
17        'your-script', // name your script so that you can attach other scripts and de-register, etc.
18        get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
19        array('jquery') // this array lists the scripts upon which your script depends
20    );
21}
22Assuming 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.
23
24WordPress questions can be asked over at WordPress Answers.
25
26https://stackoverflow.com/questions/11159860/how-do-i-add-a-simple-jquery-script-to-wordpress