wp_enqueue_script

Add and load a new script that depends on jquery. This will also force to load jquery into the page. Version is used to force reload the script and not using cached script, because "script.js?ver=1.0" is different than "script.js?ver=2.0".

<?php
// Inside a parent theme
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/my-script.js', array('jquery'), '1.0' );
// Inside a child theme
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/my-script.js', array('jquery'), '1.0' );
// Inside a plugin
wp_enqueue_script( 'custom-script', plugins_url( '/js/my-script.js', __FILE__ ), array('jquery'), '1.0' );
?>

Load scripts on frontend:

function add_scripts_frontend() {
	wp_enqueue_script( 'frontend-script', plugins_url( '/js/script.js', __FILE__ ) );  
}
add_action('wp_enqueue_scripts', 'add_scripts_frontend');

Load the jquery script from default location:

<?php
function enqueue_jquery() {
	wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery');
?>

Load the jquery script from other location:

<?php
function enqueue_jquery() {
	if (!is_admin()) { // prevent from loading in admin section
		wp_deregister_script('jquery');
		wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js');
		wp_enqueue_script('jquery');
	}
}
add_action('wp_enqueue_scripts', 'enqueue_jquery');
?>

Leave a Comment