How to include jQuery in a WordPress theme?

假如想象 提交于 2019-12-05 09:53:29

Is there any specific reason why you're not using the jQuery found in WordPress?

If you need to add your JavaScript file which depends on jQuery, you can add jQuery as a dependency.

<?php

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

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

?>

Note that WordPress loads jQuery in no conflict wrappers. so your code should be like:

jQuery(document).ready(function($) {
    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut
});

In wordpress No need for Custom Jquery. Add dependencies as 'jquery' it'll automatically get loaded.

Since WP already comes with jQuery, I would simply load it for your theme, add it like this into your functions.php

function load_scripts(){
    //Load scripts:
    wp_enqueue_script('jquery'); # Loading the WordPress bundled jQuery version.
    //may add more scripts to load like jquery-ui
}
add_action('wp_enqueue_scripts', 'load_scripts');

There are several ways to include jQuery into a theme. I always use WP bundled version which I find very simple.

try this,

<?php
    function load_external_jQuery() {
        wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery 
        $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'; // the URL to check against  
        $test_url = @fopen($url,'r'); // test parameters  
        if( $test_url !== false ) { // test if the URL exists if exists then register the external file  
            wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
        }
        else{// register the local file 
            wp_register_script('jquery', get_template_directory_uri().'/js/jquery.js', __FILE__, false, '1.7.2', true);  
        }
        wp_enqueue_script('jquery'); // enqueue the jquery here
    }
    add_action('wp_enqueue_scripts', 'load_local_jQuery'); // initiate the function 
?>
Addy

You can use the methods below to include jQuery:

wp_enqueue_script( 'jquery' );  

wp_enqueue_script( 'load-js-validate', 'foldername/jquery.js' );

Directly add in header file.<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.js"></script>

function js_scripts() {
wp_enqueue_script( 'jquery', get_template_directory_uri() . '/js/example.js');
}

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