In WordPress Development Many users often make the mistake of directly calling their scripts and stylesheets in plugins and themes.
We will show you how to properly add JavaScripts and stylesheet in WordPress.
Common Mistake :
Some user uses the function to load their scripts and stylesheets.
<?php
add_action('wp_head', 'wp_bad_script_and_css');
function
wp_bad_script_and_css() {
echo
'jQuery/css goes here';
}
?>
While the above code may seem easier, it is the wrong way of adding scripts in WordPress, and it leads to more conflicts in the future.
How Properly Enqueue Scripts in WordPress
Loading scripts properly in WordPress is very easy. Below is an example code that you would paste in your plugins file or in your theme’s functions.php file to properly load scripts in WordPress.
<?php
function
wpe_adding_scripts() {
wp_register_script('my_custom_script', plugins_url('custom_script.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('my_custom_script');
}
add_action( 'wp_enqueue_scripts', 'wpe_adding_scripts'
);
?>
How Enqueue Styles in WordPress
Just like scripts, you can also enqueue your stylesheets. Look at the example below:
<?php
function
wpe_adding_styles() {
wp_register_style('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpe_adding_styles'
);
?>
Instead of using wp_enqueue_script
, we are now using wp_enqueue_style
to add our stylesheet.