If user is not admin, deregister jQuery?

2019-07-30 01:45发布

I really hope this is not a duplicate question. I'm beginning my journey into Wordpress theme development. I've been using the Codex as documentation to write each component I create. However, I have came across a snippet which for some reason I cannot get my head across it.

if ( !is_admin() ) {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( 'ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js' ), false, null, true );
    wp_enqueue_script( 'jquery' );
}

Reading the snippet in pure English it says, if user is not admin, deregister jQuery, register it again, and queue it for output when the page is sent at the right time. Why would I want to do this when I can simply add jQuery to a set of '<script></script>' tags and be done with it?

EDIT

Should've mention where I discovered this snippet. I found it in the functions.php file on Blank Theme by http://digwp.com/2010/02/blank-wordpress-theme/

3条回答
\"骚年 ilove
2楼-- · 2019-07-30 01:49

is_admin() checks if the current page being displayed is an admin Dashboard page. To check if the user is an admin, you'd use current_user_can('administrator') -- or, even better, check for a particular capability.

The purpose of this code is to leave the version of jQuery that comes with WordPress intact for admin pages (which use a lot of jQuery & AJAX) but load a different one on themed pages. They might have been trying to load a newer version than what shipped with WordPress at the time, or they could have just been trying to get it loaded off Google's CDN.

查看更多
Fickle 薄情
3楼-- · 2019-07-30 01:51

The logic is probably:

register_unminified_jquery();
if(!admin) {
    unregister();
    register_minified_jquery();
}
查看更多
该账号已被封号
4楼-- · 2019-07-30 01:55

This script loads a specific version of jquery, actually a pretty old one as version 1.10.2 is the current up-to-date version.

Probably it is used in a plugin where some javascript functions are broken in more recent versions of jquery.

If possible, try to avoid setting scripts directly in the head with script tags. In this way it is possible to dynamic load/unload scripts (as you've demonstrated).

查看更多
登录 后发表回答