我不确定这是否可行,但我希望我可以通过 PHP 以编程方式检索 WordPress 的内置 jQuery 版本号。
我更喜欢使用 wp_register_script()
包含 jQuery 的 CDN 版本,然后我使用 WordPress 的内置 jQuery 作为后备。
使用 CDN 版本的问题是,如果 WordPress 更新其内置的 jquery 版本,CDN 版本可能不匹配。所以我希望获取版本号(可能使用 wp_default_scripts()
),然后将其传递给 wp_register_script()
。
关于我如何做到这一点有什么想法吗?
最佳答案
我借自WP jQuery Plus :
function hs_script_enqueuer() {
if( !is_admin() ) {
// Enqueue so we can grab the built-in version
wp_enqueue_script( 'jquery' );
// Get jquery handle - WP 3.6 or newer changed the jQuery handle (once we're on 3.6+ we can remove this logic)
$jquery_handle = (version_compare($wp_version, '3.6-alpha1', '>=') ) ? 'jquery-core' : 'jquery';
// Get the WP built-in version
$wp_jquery_ver = $GLOBALS['wp_scripts']->registered[$jquery_handle]->ver;
// Just in case it doesn't work, add a fallback version
$jquery_ver = ( $wp_jquery_ver == '' ) ? '1.8.3' : $wp_jquery_ver;
// De-register built-in jquery
wp_deregister_script('jquery');
// Register CDN version
wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/'. $jquery_ver .'/jquery.min.js' );
// Enqueue new jquery
wp_enqueue_script( 'jquery' );
}
}
add_action( 'wp_enqueue_scripts', 'hs_script_enqueuer' );
// Add jquery fallback if CDN is unavailable
function jquery_fallback() {
echo '<script>window.jQuery || document.write(\'<script src="' . includes_url( 'js/jquery/jquery.js' ) . '"><\/script>\')</script>' . "\n";
}
add_action( 'wp_head', 'jquery_fallback' );
关于php - 通过 PHP 在 WordPress 中获取 jQuery 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17375070/