1

I'm migrating my webpage(s) to wordpress and thus creating a theme. However, the page has a number of scripts (javascript) than need to run. Please may someone clarify my understanding.

To run the scripts I've added them to the functions.php file using the format below. I assume add_actions calls / runs the function. However, will this script run on every page? is there a way of being selective (making some scripts run on page X but not on Y).

======================================================== Functions.php

function my_theme_scripts_function() {
    wp_enqueue_script( 'myscript', get_template_directory_uri() .   '/js/myscript.js');
    }

add_action('wp_enqueue_scripts','my_theme_scripts_function')
;
1
  • Under what conditions do you want the script to be included? Commented Feb 17, 2015 at 12:17

1 Answer 1

1

In such functions, you can simply grab the current page, and make a conditional processing depending on the id, or any other characteristic of this page. For example let's say you want to apply some script on the page ID 4:

function my_theme_scripts_function() {
   global $post;
   if ($post->ID == 4) {
      wp_enqueue_script( 'myscript', get_template_directory_uri() . '/js/myscript.js');
   } 
}

add_action('wp_enqueue_scripts','my_theme_scripts_function');

You could also apply this for a page slug, the presence of a meta-data, or whatever...

Sign up to request clarification or add additional context in comments.

4 Comments

thanks poozolax, I guess I can just define a global variable and fire the function based on the condition.
just in case you don't already know it (?) the $post variable is a default, already given to you by wordpress each time you load a new page/post/media... So you just have to grab it into your function with global $post and starting from that you can retrieve everything you need about the loaded page which Wordpress always calls a $post
thanks this is a great help. My final question - is it possible to define any global variable. for example global $hompg = true; I assume global would mean the variable can be accessed from other scripts.. Many thanks
You can declare any variable you need into function.php as this file is always loaded. On another side you have a bunch of global variables that Wordpress handles for you some are listed here … To follow your example, speaking about homepage, it's easier in Wordpress to ask if (is_front_page()) than defining a global variable for yourself: this latest snipped will let you know if you're on the front-page defined in the admin panel settings...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.