1

Via functions.php, I'm trying to enqueue specific scripts and styles based on two separate page templates. Here's what I've tried:

if ( !is_page_template('page-templates/page-index.php') && !is_page_template('page-templates/page-contact-us.php') ) {

        // Map
        wp_enqueue_script('google-map', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false');
        wp_enqueue_script( 'map', get_template_directory_uri() . '/js/map.js', array('jquery'), '20160408', true );

        // Map markers
        wp_enqueue_style( 'markers-style', get_template_directory_uri() . '/js/map_markers/css/map-icons.min.css', array(), '20160409', 'all' );
        wp_enqueue_script( 'markers', get_template_directory_uri() . '/js/map_markers/js/map-icons.min.js', array('jquery'), '20160408', true );    
    }

I'm expecting the scripts to enqueue on page-index.php and page-contact-us.php when I visit the pages assigned to those page templates. They are not enqueuing at all with the current code. What am I doing wrong here?

  • what action are you hooking too? this is likely the problem... suggest it should be wp_enqueue_scripts. also note is_page_template cannot be used inside the loop. – majick Apr 12 '16 at 16:11
  • I'm working through the function: function theme_scripts() { via functions.php using the _s theme. – Sam Apr 12 '16 at 16:15
  • What do you mean with "this doesn't seem to be working"? Are the script enqueued incorrectly? Are not they enqueued at all? When do you want they be enqueued exactly, when you are in those page templates or when you are not in those page templates? – cybmeta Apr 12 '16 at 16:21
  • I'm expecting the scripts to enqueue on page-index.php and page-contact-us.php when I visit the pages assigned to those page templates. They are not enqueuing at all with the current code. – Sam Apr 12 '16 at 16:24
4

I you want the script be enqueued on page-index.php and page-contact-us.php, then you must check that that page templates are used but you are checking if they are not used.

Chagne this:

if ( !is_page_template('page-templates/page-index.php') && !is_page_template('page-templates/page-contact-us.php') ) {

with:

if ( is_page_template('page-templates/page-index.php') || is_page_template('page-templates/page-contact-us.php') ) {

The first code reads like: if is NOT page-templates/page-index.php AND it is NOT page-templates/page-contact-us.php ...

The second conditional reads like: if IS page-templates/page-index.php OR it IS page-templates/page-contact-us.php ....

You can use also an array of page templates to be checked:

if ( is_page_template( array( 'page-templates/page-index.php', 'page-templates/page-contact-us.php') ) ) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.