WordPress中如何按照分类调取不同模板

Wordpress Alan 9年前 (2015-11-01) 6877次浏览 0个评论 扫描二维码

默认的分类模板文件为category.php,但通常在开发中的需求不会这么简单

分类页面按按分类调取不同模板

如果想要不同分类调取不同分类的话,可以使用category加中间杠后接需使用该模板的分类Id号或别名(slug)来进行命名,如category-2.php或category-wordpress.php

也可以通过在category.php中通过判断id号来调用不同模板,比如

if ( is_category(array(1,2,3)) ) {
  include(TEMPLATEPATH . '/abc.php');
}else{
  include(TEMPLATEPATH . '/def.php');
}

上述方法可以还满足多个分类调用同一模板的需求,还有一种类似的方法,通过获取slug来调取对应的模板,如若模板不存在则调用默认的模板

$cat_ID = get_query_var('cat');
$cat = get_category($cat_ID);
$slug=$name = $cat->slug;
if ( '' !== locate_template( array("template-parts/category-$slug.php") ) ) {
  get_template_part( 'template-parts/category', $slug );
}else{
  get_template_part( 'template-parts/category', 'default');
}

以上代码可以精简为,因为在category-$slug.php不存在时,会自动调用该目录下的category.php

$cat_ID = get_query_var('cat');
$cat = get_category($cat_ID);
$slug=$name = $cat->slug;
get_template_part( 'template-parts/category', $slug );

文章页面按所属分类调取模板

很多时候我们需要分类下的文章页面根据不同分类使用不同的模板,类似地,我们可以通过in_category()函数来判断文章所属分类来调用不同模板,该函数中可以传入分类id,也可以使用分类别名(slug)

if ( in_category(array(1,2,3)) ) {
  include('template-parts/content-a.php');
}else {
  include('template-parts/content-b.php');
}

另外一种方法是根据所属分类别名来创建模板,如content-wordpress.php,不存在的直接调用content.php。不过这个方法存在一个问题,就是当文章属于多个分类时,需从数组中选择一个分类。

 $cat = get_the_category($post->ID); $slug = $cat[0]->slug; get_template_part('template-parts/content', $slug); 

独立页面调用不同模板

独立页面默认调用index.php作为模板,可通过新建page.php来作为独立页面模板。如果要单独为某一独立页面设置模板的话,可以在模板根目录中创建page-id.php,其中的id为该独立页面的id号。同样地,也可以采用页面别名page-slug.php的方式。

 

喜欢 (0)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址