And*_*ili 5 javascript php wordpress jquery wordpress-theming
我是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');
Run Code Online (Sandbox Code Playgroud)
所以我认为我可以将其添加为其他一些JavaScript或CSS本地资源,但我不确定这种方法,因为在这种情况下,jquery.js不是本地资源,而是一个在线资源(是同样的事情吗?)
我也有一些疑惑,因为网上搜索,我发现不同的方法将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');
Run Code Online (Sandbox Code Playgroud)
有多种方法可以将 jQuery 包含到主题中。我总是使用 WP 捆绑版本,我觉得它很简单。
为什么没有使用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' );
?>
Run Code Online (Sandbox Code Playgroud)
请注意,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
});
Run Code Online (Sandbox Code Playgroud)
尝试这个,
<?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
?>
Run Code Online (Sandbox Code Playgroud)