add javascript to wordpress functions php
Add the following code to your theme's functions.php file:
function add_custom_js() {
wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true );
}
add_action('wp_enqueue_scripts', 'add_custom_js');
Explanation:
- The add_custom_js
function is created to enqueue the custom JavaScript file.
- wp_enqueue_script
is used to enqueue the script, and it takes several parameters: the handle ('custom-js'), the path to the file using get_template_directory_uri() . '/js/custom.js'
, any dependencies (in this case, 'jquery'), version number ('1.0'), and whether to load the script in the footer ('true').
- The add_action
function is then used to add this custom script to the theme's script queue on the wp_enqueue_scripts
hook.