[英]How to include jQuery in a WordPress theme?
我是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添加到我的主題,像這樣的一個 。
你能給我一些關於如何正確完成這項任務的信息嗎?
您是否有任何特定原因沒有使用WordPress中的jQuery?
如果需要添加依賴於jQuery的JavaScript文件,可以添加jQuery作為依賴項 。
<?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在沒有沖突包裝器中加載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
});
在wordpress中不需要自定義Jquery。 將依賴項添加為“jquery”它將自動加載。
由於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捆綁版本,我覺得很簡單。
試試這個,
<?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
?>
您可以使用以下方法來包含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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.