wp_unregister and wp_enqueue

2019-04-02 06:07发布

it's been suggested to me to use wp_unregister and wp_enqueue to replace wordpress jquery library with a google hosted one (because the wordpress one was having some problems)

However, when i try to insert these into my wordpress site, it breaks my site.

Do I need to wrap them somehow?

wp_unregister_script('jquery');
wp_unregister_script('jquery-ui-core');

wp_enqueue_script('jquery', https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js);
wp_enqueue_script('jquery-ui-core', https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js);

My site has a custom folder where I can put custom functions. I tried this unsuccessfully

function googlejqueryhost(){


<?php
wp_unregister_script('jquery');
wp_unregister_script('jquery-ui-core');

wp_enqueue_script('jquery', https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js);
wp_enqueue_script('jquery-ui-core', https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js);


?>
}
add_action('wp_head', 'googlejqueryhost');

1条回答
混吃等死
2楼-- · 2019-04-02 06:11

Based on the code I've demonstrated in this blog post, how about this:

function load_jquery() {

    // only use this method is we're not in wp-admin
    if (!is_admin()) {

        // deregister the original version of jQuery
        wp_deregister_script('jquery');

        // discover the correct protocol to use
        $protocol='http:';
        if($_SERVER['HTTPS']=='on') {
            $protocol='https:';
        }

        // register the Google CDN version
        wp_register_script('jquery', $protocol.'//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2');

        // add it back into the queue
        wp_enqueue_script('jquery');

    }

}

add_action('template_redirect', 'load_jquery'

I use the template redirect hook, I wonder if that is what is causing your issues.

Either way if this doesn't work can you give more info on the issue, have you got a link to the site?

Edit

Oh, also your function opens up PHP tags when really they should already be open, see my comments...

function googlejqueryhost(){


<?php // HERE, remove this
wp_unregister_script('jquery');
wp_unregister_script('jquery-ui-core');

wp_enqueue_script('jquery', https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js);
wp_enqueue_script('jquery-ui-core', https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js);


?> // AND HERE, remove this
}

Edit 2

You'll notice your site is now correctly loading jQuery from Google's CDN, the other script has nothing to do with the jQuery library itself.

enter image description here

查看更多
登录 后发表回答