效果就是在写文章的时候选择不同的文章形式,然后打开文章的时候会调用不同文章形式的模板。
2022年更新优化代码
精简代码,更加智能不用通篇增加文章形式对应的文章模板
php
/**
* 根据文章格式调用不同的模版
* 设置了相关文章形式后,如果对应文件存在就调用,没有就调用默认的。
**/
function mytheme_load_single_style() {
global $post;
$this_post_format = get_post_format($post);
$have_post_format = array('video','image');//哪些文章形式使用不同文章页面
$path = TEMPLATEPATH . '/single-'.$this_post_format.'.php';//使用single-XX.php对应文章形式
if (in_array($this_post_format, $have_post_format) && file_exists($path)){
return $path;
}else{
return TEMPLATEPATH . '/single.php';//如果不是则使用默认文章页面,single.php
}
}
add_filter('single_template', 'mytheme_load_single_style');
旧方法
看下面就代码就清楚了,如果文章形式为如果文章形式为video ,就调用single-video.php模板;可以添加多个文章样式。
php
//文章页面
add_action('template_include', 'load_single_template');
function load_single_template($template) {
$new_template ='';
// single post template
if( is_single() ) {
global $post;
if ( has_post_format( 'video' )) {// 如果文章形式为video
$new_template = locate_template(array('single-video.php' ));// 就调用single-video.php模板
}
if ( has_post_format( 'image' )) {// 如果文章形式为image
$new_template = locate_template(array('single-image.php' ));// 就调用ssingle-image.php模板
}
// 这里可以添加其他文章形式的模板
}
return (''!= $new_template) ? $new_template : $template;
}