我正试图在特定的WP页面模板上运行一个函数。特定页面称为archive.php
。
这就是我目前在functions.php
中所拥有的
if ( is_page_template( 'bloginfo("stylesheet_directory")/archive.php' ) ) {
function add_isotope() {
wp_register_script( 'isotope', get_template_directory_uri().'/js/isotope.pkgd.min.js', array('jquery'), true );
wp_register_script( 'isotope-init', get_template_directory_uri().'/js/isotope-hideall.js', array('jquery', 'isotope'), true );
wp_enqueue_script('isotope-init');
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
} else {
function add_isotope() {
wp_register_script( 'isotope', get_template_directory_uri().'/js/isotope.pkgd.min.js', array('jquery'), true );
wp_register_script( 'isotope-init', get_template_directory_uri().'/js/isotope.js', array('jquery', 'isotope'), true );
wp_enqueue_script('isotope-init');
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
}
函数之间的区别是isotope-hideall
,它在加载页面时隐藏所有类别。当不使用if
/else
时,它会在加载页面时从所有页面模板中隐藏所有类别,这不是我想要的。因此,我使用if
/else
来定位正确的页面模板。
我尝试过以下方法,但似乎都不起作用:
is_page_template( 'archive.php' )
is_page_template( 'get_template_directory_uri()'.'/archive.php' )
我做错了什么吗,或者你对此有有效的解决方案吗?
页面可以在这里找到。
正如Pieter Goosen所指出的,archive.php是为内置的WordPress功能保留的。将文件重命名为其他文件,例如archivest.php,并确保在文件顶部命名自定义页面模板:
<?php /* Template Name: Archives */ ?>
然后,只要is_page_template('archives.php')
位于模板文件夹中的根目录上,您的代码就应该使用它。如果不在文件名前面添加任何文件夹结构,如:/folder/folder2/archives.php
。
为了避免重复两次该函数,您还应该考虑解决以下问题:
function add_isotope( $isotope ) {
wp_register_script( 'isotope', get_template_directory_uri().'/js/isotope.pkgd.min.js', array('jquery'), true );
wp_register_script( 'isotope-init', get_template_directory_uri().'/js/' . $isotope . '.js', array('jquery', 'isotope'), true );
wp_enqueue_script('isotope-init');
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
if ( is_page_template( 'archives.php' ) :
add_isotope( 'isotope-hideall' );
else :
add_isotope( 'isotope' );
endif;
这里的完整逻辑是错误的。档案以is_archive()
或更具体的条件标签is_date()
作为普通档案的目标。请注意,is_archive()
在类别、作者、标记、日期和分类页面上返回true,因此如果您只需要针对存档,则is_archive()
可能有点过于通用而无法使用
此外,条件语句应该在函数内部,而不是在函数外部,因为条件检查对于wp_enqueue_scripts
钩子来说已经太晚了。
你的代码应该像这个
function add_isotope() {
if ( is_archive() ) { // Change as needed as I said
// Enqueue scripts for archive pages
} else {
// Enqueue scripts for all other pages
}
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );