How to add custom style and script in wordpress

`wp_enqueue_scripts` is a crucial action hook in WordPress that allows you to enqueue or register scripts and stylesheets properly. It is commonly used by theme and plugin developers to load necessary CSS and JavaScript files onto the front-end of a WordPress website.

When building a theme or plugin, it’s essential to enqueue scripts and styles using this hook instead of hardcoding them into the header.php or footer.php files. Enqueuing scripts and styles using `wp_enqueue_scripts` ensures that:

1. Dependencies are managed correctly: If a script or style depends on another library, `wp_enqueue_scripts` will take care of loading them in the correct order, avoiding potential conflicts.

2. Proper versioning: You can specify a version number for your scripts and styles. When you update your theme or plugin, WordPress will automatically load the latest version, allowing users to benefit from the improvements.

3. Proper handling of script dependencies: When multiple plugins and themes enqueue scripts, `wp_enqueue_scripts` ensures that each script’s dependencies are resolved and loaded only once, preventing duplicate inclusions.

To enqueue scripts and styles, you use the `wp_enqueue_script()` and `wp_enqueue_style()` functions, respectively. These functions take care of including the files at the appropriate time and location in the HTML document.

Here’s a basic example of how to use `wp_enqueue_scripts` in a theme’s functions.php file:

 

function my_theme_enqueue_scripts() {
    // Enqueue custom JavaScript file
    wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0', true);

    // Enqueue custom stylesheet
    wp_enqueue_style('my-custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), '1.0');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

 

In this example, we’re enqueuing a custom JavaScript file called `custom-script.js` that depends on jQuery. Additionally, we’re enqueuing a custom stylesheet called `custom-style.css`.

Remember to replace the file paths with the correct ones for your theme or plugin.

By using `wp_enqueue_scripts` and properly enqueuing scripts and styles, you ensure that your code plays nicely with other themes and plugins while maintaining a structured and organized approach to loading assets on the front-end of your WordPress website.

Leave a Comment

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