is_page_template() not working in functions.php

Viewed 3914

So I've got a script that I'd like to include in only a template file. The template file is located in a folder called templates in my child theme. I thought I could do it by including an if statement in functions.php and targeting the template file by name like so:

function header_anim() {
wp_enqueue_script( 'head', get_stylesheet_directory_uri() . '/js/head.js' );
}

if( is_page_template( '/templates/home-template.php' )) {
    add_action( 'wp_enqueue_scripts', 'header_anim' );
}

However, it seems as though it's not recognizing the if statement for some reason.

2 Answers

How's it going? One thing I've done with my stylesheets that could possibly work with this script. Is structuring the if statement within the function that calls the wp_enqueue_script, and using the condition if not than return. For example:

function header_anim() {
  if( !is_page_template( '/templates/home-template.php' )){
    return;
  }
  wp_enqueue_script( 'head', get_stylesheet_directory_uri() . '/js/head.js' );
}
add_action( 'wp_enqueue_scripts', 'header_anim' );

Let me know if that works for you....

Later, Juice

Hmmm, how about this. Let's try to do the conditioning a little bit differently.... Do you have another function that is loading another script for the rest of your templates/pages? If so we can combine them into one function, and hopefully this will work...

function equeue_scripts_header () {
  if( is_page_template( '/templates/home-template.php' )){
      wp_enqueue_script( 'head', get_stylesheet_directory_uri() . '/js/head.js' );
  }
  else {
    /*call enqueue script for that corresponds to the rest of the      site */
  }
}
add_action( 'wp_enqueue_scripts', 'equeue_scripts_header' );

Hopefully I didn't just add another iteration you already tried. Let me know how this one works...

Related