wp_enqueue_script仅在某些页面模板上

时间:2019-07-09 03:15:31

标签: wordpress

我正在插件中执行此操作。我尝试以下操作仅在使用模板文件#ifndef Hello_World_H #define Hello_World_H #endif // Hello_World int x=1; using namespace std; int Hello() { cout << x << endl; return 69; } 时使脚本入队。

obj\Debug\thing.o||In function 'Z5Hellov':|
C:\0w0\Multiple file test\Hello_world.h|7|multiple definition of 'Hello()'|
obj\Debug\main.o:C:\0w0\Multiple file test\Hello_world.h|7|first defined here|
obj\Debug\thing.o||In function 'Z5Hellov':|
C:\0w0\Multiple file test\Hello_world.h|7|multiple definition of 'x'|
obj\Debug\main.o:C:\0w0\Multiple file test\Hello_world.h|7|first defined here|
||error: ld returned 1 exit status|
||=== Build failed: 5 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

}

它不起作用。它不会在任何前端页面上加载jquery文件,更不用说渲染archive-my_custom_post_type.php时了。但是,当我删除该条件add_action('wp_enqueue_scripts', 'my_enqueue'); function my_enqueue($hook) { if(is_page_template('archive-my_custom_post_type')){ wp_enqueue_script( 'ajax-scripts', plugins_url( '/js/myjquery.js', __FILE__ ), array('jquery') ); } 时,它会加载到我所有的前端页面上。

问题:每当使用自定义帖子类型档案模板时,如何对脚本进行条件入队?

2 个答案:

答案 0 :(得分:0)

您需要使用完整的文件名,包括.php。因此,在您的情况下,您将需要使用:

is_page_template('archive-my_custom_post_type.php')

此外,如果您的模板位于子目录下,则也需要指定该子目录。 参考:https://developer.wordpress.org/reference/functions/is_page_template/#more-information

答案 1 :(得分:0)

如果使用的是is_page_template函数,则还应将模板的完整路径(包括子目录)用作参数。例如,如果您的模板位于your-theme-directory / templates / template-file.php中,则应按以下方式使用它:

if(is_page_template('templates/template-file.php')){
  wp_enqueue_script( 'ajax-scripts', plugins_url( '/js/myjquery.js', __FILE__ ), array('jquery') );
}