php - 通过 PHP 在 WordPress 中获取 jQuery 版本

标签 php jquery wordpress

我不确定这是否可行,但我希望我可以通过 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/

相关文章:

php - CakePHP 3 中 MySQL 存储函数的 ORDER BY

php - 预填充 wp-login.php 用户名

php - Wordpress 选项页面中动态生成的下拉列表

c# - 排行榜,排名查询,如何返回高于/低于用户排名的行

php - 我如何引用动态创建的列表 php

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源

php - 在多个 html 文件中包含相同的页眉和页脚

javascript - toggleClass Jquery 不适用于子元素到父元素

jquery - WordPress:使用按钮将类添加到 div 元素

mysql - Docker Wordpress 不断重定向到网站的在线版本