0

On one page of my WordPress site i use a photo-gallery. For this i need a js-file. Now the js-file is loading on everypage but its just needed one this specific page with the page id 2. Now the problem is, that is_page(2) is not working in the functions.php because the page id is not set then. Is it still possible to do this via functions.php or would you just add the script in the footer.php?

function footer_scripts()
{
    // If query if current Page is not wp-login-php or admin page
    if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {

            wp_register_script('photo-gallery', get_template_directory_uri() . '/js/back-layer-photo-gallery.js', array('jquery'), '1.3', true);
            wp_enqueue_script('photo-gallery');
 
    }
}  

add_action('init', 'footer_scripts');

2 Answers 2

1

you can add this code in function.php and fill it with the slug name of your page and of your script

   // Load  conditional scripts
  function your_conditional_scripts()
  {
  if (is_page('pagenamehere')) {
    wp_register_script('scriptname', get_template_directory_uri() . 
  '/js/scriptname.js', array('jquery'), '1.0.0'); // Conditional 
script(s)
    wp_enqueue_script('scriptname'); // Enqueue it!
}
}

add_action('wp_print_scripts', 'your_conditional_scripts'); // Add 
Conditional Page Scripts
Sign up to request clarification or add additional context in comments.

Comments

1

You can use page slug instead of page ID and use 'wp_enqueue_scripts' instead of 'init'. If you are using child theme use 'get_stylesheet_directory_uri()' in place of 'get_template_directory_uri()' otherwise you can leave it as it is.

add_action('wp_enqueue_scripts', 'enqueue_script');
function enqueue_script() {
    if (is_page('page_slug_here')) { // Add slug in condition
        wp_enqueue_script('photo-gallery', get_template_directory_uri().'/js/back-layer-photo-gallery.js', array( 'jquery' ), '1.0', true);
    }
}

Comments

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.