0

I recently added a JavaScript file that pulls JSON data and updates the div tag on specific page of my WordPress, now to apply the JavaScript file to the page I added to header tag in the theme and secondly this JavaScript is getting called for every page/blog/ URL of my WordPress when I want it to execute only for specific page.

How can I have JavaScript script tag called for the specific page instead of all pages? I do not want to apply it in theme because now I am stuck with the current theme.

0

See wp_enqueue_script() for the information how to add scripts without editing the HTML.

I assume the script is already registered or you'll add all necessary parameters.

Tied to the particular page ID:

if( is_page($page_id) ) { // provide the page ID
    wp_enqueue_script('YOUR_SCRIPT_NAME'); //enqueue the script on success
}

Tied to the page slug:

$slug = get_post_field( 'post_name', get_post() ); // get the page slug
if('the-very-same-page-slug' == $slug) { // compare the slug against the very same
    wp_enqueue_script('YOUR_SCRIPT_NAME'); //enqueue the script on success
}

Tied to the page custom field (preferred):

$cf = get_post_field( 'CUSTOM_FIELD_NAME', get_post() ); // get the custom field
if( !empty($cf) ) { // see if the field exists or non-empty
    wp_enqueue_script('YOUR_SCRIPT_NAME'); //enqueue the script on success
}

You can create your own plugin to be independent of the theme. See Plugin Handbook for more.

  • When you say register you mean in my php file I should wp_register_script( 'Access to Home Online', 'http://san.gotdns.ch/function.js', array('jQuery));` ? – Ciasto piekarz Feb 7 '17 at 11:25
  • Yes. Also, you can bypass registering the script by using wp_enqueue_script() with additional parameters. – Max Yudin Feb 7 '17 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.