2014-01-21 64 views
4

我对WordPress很新,我正在弄清楚如何将jQuery包含到主题中。如何在WordPress主题中包含jQuery?

我创建下面的函数为的functions.php主题:

function load_java_scripts() { 
    // Load FlexSlider JavaScript that handle the SlideShow: 
    wp_enqueue_script('jQuery-js', 'http://code.jquery.com/jquery.js', array(), '1.0', true); 
} 
add_action('wp_enqueue_scripts', 'load_java_scripts'); 

所以我认为,我可以把它添加一些其他的JavaScript或CSS本地资源,但我不知道这个方法,因为在这种情况下,的jquery.js不是本地资源,但是是一个在线资源(是一回事吗?)

我也有一些疑惑,因为在网上我发现不同的方法将jQuery添加到我的主题搜索,像这样one

你能告诉我一些关于如何正确完成这个任务的信息吗?

+1

你为什么包括jQuery的manualy?这是不是包括在内? – timo

回答

1

试试这个,

<?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 
?> 
3

在WordPress无需自定义jQuery的。 将依赖项添加为“jquery”,它会自动加载。

1

由于WP已经自带了jQuery的,我只会加载你的主题,添加像这样到你的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'); 

有几种方式,包括jQuery的入主题。我总是使用WP捆绑版本,我觉得它非常简单。

1

您可以使用以下方法包括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 
2

有你为什么不使用jQuery的任何具体原因在WordPress发现了什么?

如果您需要添加依赖于jQuery的JavaScript文件,可以将jQuery添加为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'); 

?> 

请注意,WordPress在no conflict wrappers中加载jQuery。所以你的代码应该是这样的:

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 
}); 
+0

谢谢@RRikesh,那就是问题所在。我忽略了jQuery加载。我不知道没有冲突包装。出于某种原因,我似乎无法将您的答案标记为解决方案。 –

相关问题