How to add jQuery (or JS…) script on specific WordPress page

How to add jQuery (or JS…) script on specific WordPress page

Let’s say that you want to execute some jQuery script on a specific WordPress page – I had this case where I had to change the order of several HTML elements on a specific page, but as the website was using some sort of visual editor which adds the same classes for blocks of the same type throughout the website, the script would change the order of the elements on the whole website as well.

WordPress does have is_page conditional tag which comes handy in many situations, but if you want to include jQuery script on a particular page while using the proper wp_enqueue_script method at the same time, then you would only need to add is_page condition while enqueuing scripts in functions.php. So let’s have a look at the quick snippet which is only one of the ways on how to achieve this:

function bbird_under_test_scripts() {
    if ( is_page(15) ) {	        
        wp_enqueue_script( 'testscripts', get_stylesheet_directory_uri() . '/js/testscripts.js', array('jquery'));
add_action( 'wp_enqueue_scripts', 'bbird_under_test_scripts' );

In this case, testscripts.js will work on the page whose ID is 15.


Function Reference/wp enqueue script
Function Reference/is page