php functions and wordpress

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).

Read More

========================================================
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')
;

Related posts

Leave a Reply

1 comment

  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…