通过PHP在WordPress中获取jQuery版本

pla*_*guy 3 php wordpress jquery

我不确定这是否可行,但我希望我可以通过PHP以编程方式检索WordPress的内置jQuery版本号.

我更喜欢使用CDN版本的jQuery wp_register_script(),然后使用WordPress的内置jQuery作为后备.

使用CDN版本的问题是,如果WordPress更新其内置版本的jquery,则CDN版本可能不匹配.所以我希望获取版本号(可能正在使用wp_default_scripts()),然后将其传递给wp_register_script().

关于我如何做到这一点的任何想法?

pla*_*guy 7

我借用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' );
Run Code Online (Sandbox Code Playgroud)