Reputation: 1399
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');
Upvotes: 0
Views: 2281
Reputation: 785
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);
}
}
Upvotes: 1
Reputation: 295
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
Upvotes: 1