How to Include jQuery and CSS in WordPress Plugin and Theme Development?

Looking for a short tutor on how to include jQuery and CSS while developing the WordPress plugin or theme? Here is the safe way of attaching your stylesheet and including jquery, along with this here I’ve also discussed on how to add your own jquery script in your plugin or theme. Before moving to our main topic let me mention the bad practice of adding jquery and CSS in wordpress plugin and theme developmet.

Also read:

Top 5 Free and Premium Chat Plugins for WordPress

Bad Practice of Adding JQuery and CSS in WordPress Plugin and Theme Development

If you are echoing the jquery or CSS in your wordpress plugin and theme development then this one is the wrong way of adding the stuff. Here is a sample of bad practice of adding jquery and CSS in wordpress development.

<?php
echo ‘<script src="http://code.jquery.com/jquery-1.9.1.js"></script>’
echo ‘<link href="’. plugins_url( 'css/mystyle.css' , __FILE__ ) . '" rel="stylesheet" type="text/css" />’;
?>

Proper Way of Adding JQuery and CSS in WordPress Plugin and Theme Development

We just had a look at the wrong way of adding CSS and jquery, then how to add them in proper way in wordpress plugin and theme development? WordPress comes with some useful functions that let you safely add the style sheets and jquery. wp_enqueue_script(), wp_register_style() and wp_enqueue_style() built-in functions makes your job easy. These functions should be used along with ‘wp_enqueue_scripts’ hook. Here is the sample code which uses these functions and hook to add jquery and CSS in wordpress plugin developmet-

<?php
function my_scripts() {
wp_enqueue_script( 'jquery' );
wp_register_style( 'prefix-style', plugins_url('mystyle.css', __FILE__) );
wp_enqueue_style( 'prefix-style' );
}
add_action('wp_enqueue_scripts','my_scripts');
?>

In the code above, we added jQuery with  wp_enqueue_script function, we have also included our own CSS file using  wp_register_style and wp_enqueue_style functions, all you need is to replace ‘prefix-style’ handle and  ‘mystyle.css’ with your own CSS file name.

Just add the code written below in my_scripts() function to include your own jquery script in wordpress plugin development

wp_enqueue_script('newscript',plugins_url( 'myscript.js' , __FILE__ ),array( 'jquery' )); //replace myscript.js with your script file name

Replace plugins_url() with get_template_directory_uri() if you want use the code above for theme development.

WordPress comes pre-installed with jquery and many other popular scripts so it is not required to add the jquery CDN, just add wp_enqueue_script( ‘jquery’ ); that’s it.

Leave a Reply

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


six − 3 =

Love This Article? Spread It.
X
Hey.. Wanna Subscribe?