Wordpress Theming: add custom scripts and jquery the correct way

£可爱£侵袭症+ 提交于 2019-12-05 13:32:30

The best way to avoid asset conflicts is by properly enquing the files. To do this you must use wp_enqueue_script

a good way to do this is to put it as part of a function in your functions.php file like so

  1. create a function
  2. insert wp_register_script into the function
  3. then insert wp_enqeue_script into the function
  4. use add_action(), to initlize the enqueue-ing process

so -

function load_scripts() {
  wp_register_script( 'script-name', get_template_directory_uri() . '/js/script.js', array( 'scriptyouwillwaittobeloaded' ) );
  wp_enqueue_script( 'script-name' );
}

add_action('wp_enqueue_scripts', 'load_scripts');

In this example the function load_scripts() would then be called in the header.php file. Take a look at wp_register_script as well to get a better understanding of the arguments for that as well, but in summary -

first argument: is the name you want to use as reference to this script

second argument: is the actual link to the script

third argument: is the script that you want to load before this script (the script you want to wait for before this script loads)


and for wp_enqueue_script, the argument is merely a reference to the name (the first argument of wp_register_script)


the add_action function arguments:

first argument: the function you are "hooking" into

second argument: the function you created that will be "hooked"


To note - you can load as many scripts as you would like in this function, this is just an example of loading a single script.

What it looks like the dev's did was just to use a simple reference. If you would like to enqueue a WP script look at wp_enqueue_script

I don't believe the scripts will depend on anything other than a specific version of jquery.

this is how they do it:

<?php

function my_scripts_method() {
    wp_enqueue_script(
    'custom-script',
    get_stylesheet_directory_uri() . '/js/custom_script.js',
    array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!