is_page_template()在functions.php中不起作用

时间:2017-10-08 01:04:52

标签: php wordpress wordpress-theming

所以我有一个脚本,我只想包含在一个模板文件中。模板文件位于我的子主题中名为templates的文件夹中。我想我可以通过在functions.php中包含if语句并按名称定位模板文件来实现:

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

然而,似乎由于某种原因它没有认识到if语句。

2 个答案:

答案 0 :(得分:1)

怎么样?我用我的样式表完成了一件可能与这个脚本一起工作的事情。是在调用wp_enqueue_script的函数中构造if语句,如果不是return则使用条件。例如:

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

如果这对您有用,请告诉我....

后来 汁

答案 1 :(得分:0)

嗯,嗯,这个怎么样。让我们尝试稍微改变一下条件....你有另一个函数正在为其余的模板/页面加载另一个脚本吗?如果是这样,我们可以将它们组合成一个函数,希望这可以工作......

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

希望我不只是添加你已尝试过的另一个迭代。让我知道这个是如何工作的......

相关问题