简体   繁体   中英

Difference between wp_register_style() and wp_enqueue_style

I'm new to WordPress development. While going through some example codes I came across wp_register_style() , used to register a stylesheet and its location which can be called later using wp_enqueue_style() .

But going through the documentation of wp_enqueue_style() , it says "Registers the style if source provided (does NOT overwrite) and enqueues".

So my question is what is the difference in both the techniques. Is it correct to use the wp_enqueue_style() directly instead of registering and then calling using wp_register_style() and wp_enqueue_style() . Is there something I'm missing.

This means, if you want to register your scripts, but not directly load them in your pages, you can register the files once, and then load them when you need them.

For example:

You have a switch statement which loads some functionality, but two of three cases needs a particular javascript file, and one doesn't. You can enqueue the script every time, which costs more resources, or just enqueue the script when you need it:

...
wp_register_script( 'my-handy-javascript', ... );
...
switch( $somevar ) {
    case 'value':
        wp_enqueue_script( 'my-handy-javascript' ); // needs the file
        ...
    break;
    case 'value2':
        wp_enqueue_script( 'my-handy-javascript' ); // needs the file
        ...
    break;
    default:
    case 'value3': // doesn't needs the file
        ...
    break;
}

It is not necessary to register a script and then enqueue them, but it can provide some logic in your code if you register all the scripts you need somewhere in your functions.php instead of everywhere in your code.

The Codex also tells the following:

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side.

This means that if you want to enqueue your script on the front-end and in the back-end, you can register a script once, and then load it on the front-end with wp_enqueue_script and in the back-end with admin_enqueue_script. This way you won't have the same enqueue recourse twice in one theme, plugin, widget or whatever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM