Include custom CSS and jQuery on a WordPress page or post

Include this function in your child theme’s functions.php script.

function my_theme_scripts() {
     if(is_page(12)){
          wp_enqueue_script(‘my_script’, get_stylesheet_directory_uri().’/js/my_script.js’, array( ‘jquery’ ));

          wp_enqueue_script(‘my_css’, get_stylesheet_directory_uri().’/css/my_css.css’));
     }
}
add_action(‘wp_enqueue_scripts’, ‘my_theme_scripts’);

my_css.css is a reference to your custom stylesheet and my_script.js is a reference to your custom jQuery script. The array(‘jquery’) parameter tells the enqueue function that my_script is dependent on jQuery and tells the enqueue function to load the script after jQuery loads. This will work for any page or post. The is_page() function  checks for a page ID which in this case is 12.

Make sure you use ‘jQuery’ instead of ‘$’ in your jQuery scripts. Here is an example jQuery script:

jQuery(document).ready(function () {
console.log(‘div width: ‘ + jQuery(window).width());
});

Advertisements

Published by

angelo bonavera

Hi I'm a web developer and I run a web hosting company called 2slick.com.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s