How To Use wp_enqueue_script () hook to Add js and CSS files

Sunday , 18, April 2021 Leave a comment

we will know how to include a wp_enqueue_script() hook into your WordPress site?

wp_enqueue_script() WordPress hook use to include JavaScript and CSS files in WordPress.

How Enqueueing Works

There are two steps taken when enqueueing a script or a style. First you register it – Show the path– and then you use actually enqueue ,that is standert rool of wordpress , finally show outputs it into the header or just before the closing body tag.

wp_enqueue_scripts Basics 

The wp_enqueue_scripts hook use to enqueue scripts and styles in the front-end . Within the hooked function you can use the wp_register_script(), wp_enqueue_script(), wp_register_style() ,wp_enqueue_style().

function function_enqueue_scripts() {
    wp_register_style( 'custom-style', get_template_directory_uri().'/css/all.css');
    wp_register_script( 'custom-js', get_template_directory_uri().'/js/main.js') );

    wp_enqueue_style( 'custom-style' );
    wp_enqueue_script( 'custom-js' );
}
add_action( 'wp_enqueue_scripts', 'function_enqueue_scripts' );

In the example above I registered and enqueued the assets within the same function ,In fact, you can use the enqueue functions only to register and enqueue functions

add_action( 'wp_enqueue_scripts', 'function_enqueue_scripts' );
function function_enqueue_scripts() {
    wp_enqueue_style( 'custom-style', get_template_directory_uri().'/css/all.css');
    wp_enqueue_script( 'custom-js', get_template_directory_uri().'/js/main.js') );;
}

Scripts In The Footer

This increases apparent page load times and can prevent your website from hanging while loading scripts, especially if they contain AJAX calls.

The enqueuing mechanism can add scripts to the footer using the fifth parameter

function function_enqueue_scripts() {
    wp_enqueue_script( 'all',get_template_directory_uri() .  '/js/all.min.js',' ','',true);
}
add_action( 'wp_enqueue_scripts', 'function_enqueue_scripts' );

wp_enqueue_script()

in this function five parameters ,the first parameter to call a unique Name of the script , it is Required . second parameter for src script path. last parameter is bool ,before </body> instead script ‘true’ but in the <head>. Default ‘false’.

Some Useful Path Directory

get_template_directory_uri() is Retrieves template directory URI for current theme.

get_stylesheet_uri() a stylesheet file name is ‘style.css’ which is appended to the stylesheet directory URI path.

plugins_url is retrieves a URL within the plugins or mu-plugins directory.

Fix the Error Establishing a Database Connection in WordPress The Ultimate Guide to WordPress Shortcodes after_setup_theme WordPress hook best wordpress security plugins 2021
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *