wordpress 覆盖模板层次结构
wordpress override template hierarchy
我有一个自定义 post 类型 "accommodation" 和一个自定义分类法 "tax_destination"。
当我把这个 url:
/?post_type=accommodation&tax_destination=granada
呈现的模板是:taxonomy-tax_destination.php
是否可以使用 archive-accommodation.php 代替?
我想要的是使用存档模板显示该分类的住宿列表。
WordPress 有一个名为 template_include
that allows you to override which template files are included on a particular request. You can combine that with a check using is_tax()
的便捷过滤器。 $term
参数是可选的,但由于您包含了一个我将包含它所以它仅适用于 granada
术语:
add_filter( 'template_include', 'accommodation_template', 99 );
function accommodation_template( $template ) {
if( is_tax( 'tax_destination', 'granada' ) ){
$new_template = locate_template( array( 'archive-accommodation.php' ) );
if( !empty( $new_template ) ){
return $new_template;
}
}
return $template;
}
如果将其放入 functions.php
文件中,它将确定当前请求是否针对分类法 tax_destination
中的术语 granada
,以及 return archive-accommodation.php
模板。
注意:如果您在其他 post 类型上重复使用那些 tax/terms,您可能还需要在 if 语句中包含 is_post_type_archive( 'accommodation' )
或 get_post_type() == 'accommodation'
。
我有一个自定义 post 类型 "accommodation" 和一个自定义分类法 "tax_destination"。 当我把这个 url:
/?post_type=accommodation&tax_destination=granada
呈现的模板是:taxonomy-tax_destination.php
是否可以使用 archive-accommodation.php 代替?
我想要的是使用存档模板显示该分类的住宿列表。
WordPress 有一个名为 template_include
that allows you to override which template files are included on a particular request. You can combine that with a check using is_tax()
的便捷过滤器。 $term
参数是可选的,但由于您包含了一个我将包含它所以它仅适用于 granada
术语:
add_filter( 'template_include', 'accommodation_template', 99 );
function accommodation_template( $template ) {
if( is_tax( 'tax_destination', 'granada' ) ){
$new_template = locate_template( array( 'archive-accommodation.php' ) );
if( !empty( $new_template ) ){
return $new_template;
}
}
return $template;
}
如果将其放入 functions.php
文件中,它将确定当前请求是否针对分类法 tax_destination
中的术语 granada
,以及 return archive-accommodation.php
模板。
注意:如果您在其他 post 类型上重复使用那些 tax/terms,您可能还需要在 if 语句中包含 is_post_type_archive( 'accommodation' )
或 get_post_type() == 'accommodation'
。