Loading scripts in WordPress with wp_enqueue_scripts

July 19, 2016
Category: TIL
Tags: PHP and WordPress

Sometimes you need to put scripts on a specific page in WordPress. Frameworks like Genesis have boxes where you can add header or footer scripts. Most don’t, though. Here is how to load scripts on specific pages in WordPress with the wp_enqueue_scripts hook.

In functions.php in your theme folder, you’ll need to add an action for the wp_enqueue_scripts hook. This will be a function pointing to the script.

I’m using get_stylesheet_directory_uri() to link to the script. This means if your theme’s main style.css is in “example.com/wp_content/themes/twentysixteen/style.css”, your script should be in “example.com/wp_content/themes/twentysixteen/js/script.js”.

Pick one the the scenerios below and add the code to your functions.php file in your theme. Make a backup of it first in case you mess something up.

This will work for the whole site:

 function hello_script() { wp_register_script(
'hello-script', get_stylesheet_directory_uri() . '/js/hello-script.js' );
wp_enqueue_script( 'hello-script' ); } add_action( 'wp_enqueue_scripts',
'welcome_page_script' ); 

This will work for just a specific page. Switch “052” with your page ID. Here is how you find the page ID.

 function about_page_script() { if ( is_page('052') ) {
wp_register_script( 'about-script', get_stylesheet_directory_uri() .
'/js/about-script.js' ); wp_enqueue_script( 'about-script' ); } } add_action(
'wp_enqueue_scripts', 'about_page_script' ); 

If you have one of those fancy themes that generates a front page that you edit in the Customizer but it doesn’t have a page ID, but you only want it to display on the front page, don’t fret. WordPress has a is_front_page function:

 function front_page_script() { if ( is_front_page() ) {
wp_register_script( 'front-page-script', get_stylesheet_directory_uri() .
'/js/front-page-script.js' ); wp_enqueue_script( 'front-page-script' ); } }
add_action( 'wp_enqueue_scripts', 'front_page_script' ); 

Find this post useful?

Buy me a coffeeBuy me a coffee