You are Viewing : HomeCSSIncluding Javascript and CSS in wordpress – The ultimate guide

Including Javascript and CSS in wordpress – The ultimate guide

WordPress provides a lot of coding convenience for a beginning developer. This guide explains the clean and proper way of including your Javascript and CSS with your wordpress themes and plugins.

Including scripts

The traditional method is by using the <script></script> tag.

Example.

<script src="http://example.com/scripts/script.js" type="text/javascript"></script>

With wordpress, procedure of including and managing scripts have never been more tidier.

WordPress ships with a lot of included scripts, though some of them might not be up to date. Script related wordpress functions are

      1. wp_register_script()
      2. wp_enqueue_script   Codex()
      3. wp_deregister_script()

Click the respective functions for usage and parameters. These functions and others listed below are entered in your theme’s functions.php.

These functions are best understood with examples.

Example below, Include a script that comes with wordpress. e.g. jQuery or prototype.

 <?php
// All of these goes in functions.php
function load_inbuilt_scripts() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('prototype');
}

add_action('init', 'load_inbuilt_scripts');
?>

Example below, Load your own script to replaces the built-in one.

 <?php
function my_own_incl_scripts() {
	// remove the inbuilt one first.
    	wp_deregister_script('jquery');
	// assign theme directory url to a variable
	$themedir = get_bloginfo('template_url');
	wp_enqueue_script('jquery', $themedir . "/scripts/jquery/jquery.js");
}

add_action('init', 'my_own_incl_scripts');
?>

Load a script from alternate location e.g. google AJAX CDN or any remote server. Thereby replacing the inbuilt one.

 <?php
function load_remote_scripts() {
	wp_deregister_script('jquery'); //remove the in built one first.
	// Include the google cdn jQuery
	wp_enqueue_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js");
	// Load mootools from A remote server. Notice the script name.
	wp_enqueue_script('moo', "https://example.com/cdn/js/mootools.js");
}

add_action('init', 'load_remote_scripts');
?>

Example below, on Loading a script with wp_enqueue_script() and arguments.

 <?php
/* Say you need the script -
		* named "my_dep_script"
		* located in ""/scripts/cool/accord.js"
		* which is dependent on jQuery framework
		* and of version 1.2.3,
		* should be loaded in footer.
*/
function script_with_args() {
	wp_enqueue_script(
		'my_dep_script', // name of the script
		get_bloginfo('template_url') ."/scripts/accord.js", // location
		array('jquery'), //dependencies
		'1.2.3', // script version
		true); // load in footer.( wp_footer() must be present!)
}

add_action('init', 'script_with_args');
?>

Including styles

Well, procedure is similar to scripts above. Style related functions are

      1. wp_register_style()
      2. wp_enqueue_style()

It is done with the wordpress function wp_enqueue_style() (codex reference).

Example below, Load a stylesheet file “my_style.css” from scripts sub folder.

 <?php
function load_my_styles() {
	// assign the url of theme to a variable $themedir
	$themedir = get_bloginfo('template_url');
	wp_enqueue_style( 'my_style',  $themedir . "/styles/my_style.css");
	}

// Load the above function via init hook.
add_action('init', load_my_styles);
?>

Example below, Load a style with wp_enqueue_style and arguments.

 <?php
function load_style_args() {
	$themedir = get_bloginfo('template_url');

	wp_enqueue_style(
		// Arg 1) name that wordpress refers to.
		'my_style_2',
		// Arg 2) URL to theme directory
		$themedir . "/styles/my_style_2.css",
		// Arg 3) its dependencies. Loaded in previous function.
		array('my_style'),
		// Arg 4) version of the style
		'0.1.2' ,
		// Arg 5) type : media, Other - print, all.
		screen );
}

add_action( 'init', 'load_style_args');
?>

Usage and Argument of above functions

wp_enqueue_script and wp_register_script both act similar, except that the url(second argument) is optional for the former.

Example usage of wp_enqueue_script() function with arguments.

 <?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
// $handle : Name that wordpress handles this script with.
// $src : location of the script file, if it's not included already.
// $deps : Other scripts THIS scripts depends upon. Default - array()
// $ver : Version of the script. Optional. - Default - WordPress version.
// $in_footer : Loads the script in footer. - Default - false.
?>

As like the script handling functions above, similar are wp_enqueue_style and wp_register_style.

Example usage of wp_enqueue_style() with parameters.

 <?php
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
// $handle : Name of the stylesheet.
// $src : Path to the stylesheet.
// $deps : Styles that should be loaded before this style.
// $ver : Version of the style.
// $media : screen , media, handheld or print.
?>

Using Javascript and CSS in wordpress admin pages

You can use the is_admin() function of wordpress to load the javascript and css only in admin pages. Quite useful for plugin and theme developers.

An example.

 <?php
if( is_admin()) {
	// scripts and styles for wp-admin here.
	// This loads only on admin pages.
	wp_enqueue_script('jquery');
	wp_enqueue_script('admin_fx',
	$themedir . "/scripts/admin/admin.js");
	wp_enqueue_style('my_admin_css', $themedir . "/styles/admin/admin_styles.css");
}

if( !is_admin()) {
	// scripts and styles for regular wordpress pages.
	wp_enqueue_script('mootools');
	wp_enqueue_style('my_blog.css');
}
?>

Above function loads the scripts and styles globally in all admin pages e.g. Dashboard, Appearance, Plugins, settings sections.

But, what if you want to include a javascript file to a single admin page(e.g. Theme options)? It is not that hard. Trust me.

Example

 <?php // Functions.php
// This adds the options page to the admin_menu hook.
add_action('admin_menu', 'theme_admin_page');

// Example options.page - Define the location and section.
function theme_admin_page() {
	$page = add_submenu_page(
			'themes.php',
			'Great Theme Options',
			'Customize theme',
			'edit_themes',
			'options',
			'theme_options_page'
			);
	// Add the scripts and styles ONLY to options page.
	add_action('admin_print_scripts-'. $page, 'options_includes');
}

function options_includes(){
	if ( is_admin()) {
		wp_enqueue_style('admin_css_own', get_bloginfo('template_url') . "/styles/my_style.css");
		wp_enqueue_script('scriptaculous');
		wp_enqueue_script('admin_fx', get_bloginfo('template_url') . "/scripts/admin_fx.js", array('scriptaculous'), '0.2.3', true );
	}
}

function theme_options_page(){
	echo '<div class="wrap">';
	echo '<div id="icon-tools" class="icon32"></div>';
	echo '<h2>Sample Theme Options</h2>';
	echo "<p> Hello there! This is your admin page</p>";
	// Form goes here.
	echo "</div><!-- end the wrap container -->";
}
?>

That does the job.

Selective use of Javascript and CSS

There might be some situations when you want to run  javascript code on a single type of page. For example : you might want to include a script that runs only on Author pages. You can do it with the conditional tag is_author() and wp_enqueue_script() function. Usage is similar to the is_admin() above.

Likewise, with conditional tags you can selectively use Javascript and css in wordpress.

Notes and Troubleshooting

  1. When you replace the jQuery that ships with wordpress, make sure to use noConflict mode. This allows simultaneous usage of other script libraries. More about this here.
  2. When your script is not working, check whether it is loaded. You can use Firefox’s Firebug extension (or Chrome’s Inspect element so). Look under the “Net” Panel –>  “JS” tab for any 404 not found error(Colored Red). If it is a 404, then check whether the path to the script is correct. Double check the variables and concatenation, if you use them. If not, there must be something wrong with the javascript code. Most common culprits are spelling errors and case-sensitivity.
  3. Check with firebug for any duplicate scripts. Plugins may sometimes use a different version of the same library that you use.
  4. It is recommended to load the scripts in the wp footer. You can do this with $in_footer (5th) argument of wp_enqueue_script.
  5. Always perform these procedures on a locally installed wordpress(PC, Mac), or at least on an alternate wordpress installation.

Conclusion

The purpose of this guide is to provide organized information that is often vague and scattered through out the web. If you have any questions/ wish to correct me, or criticism which i really appreciate, Please do.

Beginners learning Javascript can make use of these books – JavaScript: The Definitive Guide by David flanagan, or JavaScript: The Good Parts by Douglas Crockford. While Complete knowledge of javascript is not needed nowadays, because of availablity of multiple javascript frameworks such as jQuery, prototype. But it does serve build a strong base for the frameworks.
 

  • http://www.facebook.com/profile.php?id=100002915522199 Zainal Kl

    http:/fortysevenrobots.com/wordpress/fluency-admin

  • http://www.facebook.com/profile.php?id=100002915522199 Zainal Kl

    http:/fortysevenrobots.com/wordpress/fluency-admin