0
0
Wordpressframework~5 mins

Enqueuing styles and scripts in Wordpress

Choose your learning style9 modes available
Introduction

Enqueuing styles and scripts in WordPress helps you add CSS and JavaScript files safely and properly to your website. It avoids conflicts and ensures files load in the right order.

You want to add a custom CSS file to style your WordPress theme.
You need to include a JavaScript file for interactive features on your site.
You want to load a library like jQuery or a plugin script without breaking other parts of the site.
You want to make sure your styles and scripts only load on certain pages to keep the site fast.
You want WordPress to manage dependencies and versions of your CSS and JS files automatically.
Syntax
Wordpress
<?php
function my_theme_enqueue() {
    wp_enqueue_style('handle-name', get_template_directory_uri() . '/css/style.css', array(), '1.0', 'all');
    wp_enqueue_script('handle-name', get_template_directory_uri() . '/js/script.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue');

wp_enqueue_style adds a CSS file.

wp_enqueue_script adds a JavaScript file.

Examples
This loads the main style.css file of your theme.
Wordpress
<?php
wp_enqueue_style('main-style', get_stylesheet_uri());
This loads a custom JavaScript file in the footer (true means load before ).
Wordpress
<?php
wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array(), '1.2', true);
This loads a Google Fonts stylesheet from an external URL.
Wordpress
<?php
wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css?family=Roboto', array(), null);
Sample Program

This code adds a CSS file named my-style.css and a JavaScript file named my-script.js to your WordPress theme. The script depends on jQuery and loads in the footer for better performance.

Wordpress
<?php
function enqueue_my_assets() {
    wp_enqueue_style('my-style', get_template_directory_uri() . '/css/my-style.css', array(), '1.0', 'all');
    wp_enqueue_script('my-script', get_template_directory_uri() . '/js/my-script.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_my_assets');
OutputSuccess
Important Notes

Always use wp_enqueue_style and wp_enqueue_script instead of hardcoding links in header or footer.

Use the wp_enqueue_scripts action hook to add your styles and scripts.

Setting the last parameter of wp_enqueue_script to true loads the script in the footer, which helps page speed.

Summary

Enqueuing is the safe way to add CSS and JS files in WordPress.

Use wp_enqueue_style for styles and wp_enqueue_script for scripts.

Hook your enqueue function to wp_enqueue_scripts to load files properly.