最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - Enqueue script if not page template

programmeradmin1浏览0评论

I'm using the following code in functions.php:

if ( !is_page_template( 'page-full-width.php' ) ) {
    wp_enqueue_script( 'flickity-js', get_template_directory_uri() . '/js/flickity.js', array(), filemtime( get_stylesheet_directory() . '/js/flickity.js' ), true );
}

I'm expecting the script not to enqueue if the page template is set to page-full-width.php. When I check on the front-end, the script is still present.

What am I doing wrong here?

I'm using the following code in functions.php:

if ( !is_page_template( 'page-full-width.php' ) ) {
    wp_enqueue_script( 'flickity-js', get_template_directory_uri() . '/js/flickity.js', array(), filemtime( get_stylesheet_directory() . '/js/flickity.js' ), true );
}

I'm expecting the script not to enqueue if the page template is set to page-full-width.php. When I check on the front-end, the script is still present.

What am I doing wrong here?

Share Improve this question asked May 14, 2020 at 10:42 SamSam 2,1963 gold badges30 silver badges59 bronze badges 2
  • Can you check if the page-full-width.php is in the root folder of the active theme? – made2popular Commented May 14, 2020 at 10:47
  • Yep, it's in the root of the theme. – Sam Commented May 14, 2020 at 10:56
Add a comment  | 

1 Answer 1

Reset to default 0

You need to pass it as a function, or you already have but didn't copy the whole code? If you did not do it, it should look something like this

function page_template_not_enqueue() {
   if ( !is_page_template( 'page-full-width.php' ) ) {
    wp_enqueue_script( 'flickity-js', get_template_directory_uri() . '/js/flickity.js', 
array(), filemtime( get_stylesheet_directory() . '/js/flickity.js' ), true );
}
}

add_action('wp_enqueue_scripts', 'page_template_not_enqueue');

is_page_template function won't work if you have not defined a page as a Wordpress template, you can read up on that here, in short, your page templates need to start with this

<?php
/*
Template Name: Page Full Width
Template Post Type: page
*/
// Page code here...

If this still doesn't work you can try getting the template name with the global $template var, I have not experimented with this second option, I suggest you just make your page template a custom word template with this comment I posted above, but if I was to try and go the other way around I would probably try to do something like this

   function page_template_not_enqueue() {
       global $template

       if ( basename( $template ) === 'page-full-width.php' ) {
        wp_enqueue_script( 'flickity-js', get_template_directory_uri() . '/js/flickity.js', 
    array(), filemtime( get_stylesheet_directory() . '/js/flickity.js' ), true );
    }
    }

    add_action('wp_enqueue_scripts', 'page_template_not_enqueue');
发布评论

评论列表(0)

  1. 暂无评论