How to use wp_enqueue_scripts in WordPress

GOAL

To understand what wp_enqueue_scripts() is and how to use it in WordPress

Environment

WordPress5.5.3

What is wp_enqueue_scripts?

‘wp_enqueue_scripts’ is one of the hooks built in WordPress. It can be used by hooking some function. Please visit “What is Hook in WordPress?” for details about hooks.

Reference: wp_enqueue_scripts in wordpress.org

When is it used?

‘wp_enqueue_scripts’ can be used to register and enqueue When calledscripts(.js) or stylesheet(.css) to your theme. It call attached function with add_action( ‘wp_enqueue_scripts’, ‘attached_function_name‘ );

Functions wp_register_script(), wp_register_style(), wp_enqueue_script() and wp_enqueue_style() can be used in the function attached to ‘wp_enqueue_scripts’.

register

Register functions registers a script(js file) or stylesheet(css file) to use later on WordPress.

enqueue

Enqueue function add registered script or stylesheet to the queue in which enqueued scripts and stylesheets are outputted in the header.

Why is is used?

That’s because it is better to register script once and use it in some different pages. While if you embed scripts and stylesheets directly in header php file, the scripts and stylesheets are loaded in all pages, sometimes you’d like to use scripts only one page or use different scripts in a special case.

How to use wp_enqueue_scripts

Add add_action( ‘wp_enqueue_scripts’, ‘my_enque_function’ ); in functions.php of your theme and define my_enque_function to register and enqueue scripts and stylesheets.

add_action( 'wp_enqueue_scripts', 'my_enque_function' );
function my_enque_function() {
    wp_register_style('mystyle', 'dir_name/css/style.css' );
    wp_register_script('myscript', 'dir_name/js/myfunc.js' );
    wp_register_style('font-styles', 'https://fonts.googleapis.com/css2?family=Open+Sans:ital@0;1&family=Roboto+Slab:wght@600;700&display=swap');
    wp_enqueue_style('mystyle');
    wp_enqueue_script('myscript');
    wp_enqueue_style('font-styles');
}

Register function can be omitted by using src arguments. Incidentally, the argument src is required in wp_register_style() and wp_register_script().

add_action( 'wp_enqueue_scripts', 'my_enque_function' );
function my_enque_function() {
    wp_enqueue_style('mystyle', 'dir_name/css/style.css' );
    wp_enqueue_script('myscript', 'dir_name/js/myfunc.js' );
    wp_enqueue_style('font-styles', 'https://fonts.googleapis.com/css2?family=Open+Sans:ital@0;1&family=Roboto+Slab:wght@600;700&display=swap');
}