Adding JavaScript (JS) to WordPress pages is a common task for many developers, but sometimes it may be necessary to add JS only to specific pages, and not to others. There are a few different ways to accomplish this in WordPress, and in this article, we will go over the most common methods for adding JS to specific pages while excluding others.

  1. Using the wp_enqueue_script() function

One of the most common ways to add JS to specific pages in WordPress is by using the wp_enqueue_script() function. This function is used to enqueue scripts and styles in WordPress, and it allows you to specify a “handle” for the script, which can be used to target the script to specific pages.

For example, the following code shows how to enqueue a script and target it to a specific page using the wp_enqueue_script() function:

Copy codeif ( is_page( 'about-us' ) ) {
    wp_enqueue_script( 'about-us-script', get_template_directory_uri() . '/js/about-us.js', array(), '1.0.0', true );
}

In this example, the script “about-us-script” is enqueued only if the current page is the “about-us” page. The script is located at “js/about-us.js” in the theme’s directory.

  1. Using the wp_footer() function

Another way to add JS to specific pages in WordPress is by using the wp_footer() function. This function is used to add content to the footer of a WordPress page, and it can be used to add JS code directly to the footer of a specific page.

For example, the following code shows how to add JS to a specific page using the wp_footer() function:

Copy codeif ( is_page( 'about-us' ) ) {
    add_action( 'wp_footer', 'about_us_javascript' );
}

function about_us_javascript() {
    echo '<script>console.log("about us page")</script>';
}

In this example, the function “about_us_javascript” is added to the wp_footer action only if the current page is the “about-us” page. The function will output a JavaScript console log message.

  1. Using conditionals and template tags

Another way to add JS to specific pages in WordPress is by using conditionals and template tags. WordPress has several template tags that can be used to determine what type of page the current page is, and conditionals can be used to target specific pages.

For example, the following code shows how to add JS to a specific page using conditionals and template tags:

Copy codeif ( is_page( 'about-us' ) ) {
    echo '<script>console.log("about us page")</script>';
}
(Visited 31 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window