简体   繁体   中英

WordPress add JavaScript just to one page via functions.php

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

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

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM