注意:本教程要求您编辑WordPress主题文件。如果您之前没有这样做,那么请查看我们的教程,了解如何在WordPress中复制和粘贴代码。
话虽如此,让我们来看看如何在WordPress中轻松创建自定义单个帖子模板。
| 
 1 
2 
3 
4 
五 
6 
7  | 
<?php/* * Template Name: Featured Article * Template Post Type: post, page, product */  get_header();  ?> | 
wpb-single-post.php桌面。
接下来,您需要使用FTP客户端将其上传到当前的WordPress主题文件夹。
之后,您可以登录您的WordPress管理区域并创建或编辑帖子。在帖子编辑屏幕上向下滚动一下,您会注意到新的“帖子属性”元框,其中包含选择模板的选项。
您将看到那里列出的“特色文章”自定义模板。
现在你的模板基本上是空的,所以选择它只会显示一个白色的屏幕。
我们解决这个问题。
最简单的方法是从主题的single.php文件中复制代码并将其用作起点。
打开single.php文件,然后复制该get_header()行之后的所有内容。
将此代码粘贴到最后的wpb-single-post.php文件中。现在,您可以保存此文件并将其上传回服务器。
但是,这与您当前的单个帖子模板完全相同。您现在可以开始更改自定义单个帖子模板。
您可以添加自己的自定义CSS类,删除侧边栏,创建全宽模板或任何您想要的内容。
| 
 1 
2 
3 
4 
五 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
三十  | 
/** Define a constant path to our single template folder*/define(SINGLE_PATH, TEMPLATEPATH . '/single');/*** Filter the single_template with our custom function*/add_filter('single_template', 'my_single_template');/*** Single template function which will choose our template*/function my_single_template($single) {global $wp_query, $post;/*** Checks for single template by category* Check by category slug and ID*/foreach((array)get_the_category() as $cat) :if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';endforeach;} | 
| 
 1 
2 
3 
4 
五 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29  | 
/*** Define a constant path to our single template folder*/define(SINGLE_PATH, TEMPLATEPATH . '/single');/*** Filter the single_template with our custom function*/add_filter('single_template', 'my_single_author_template');/*** Single template function which will choose our template*/function my_single_author_template($single) {global $wp_query, $post;/*** Checks for single template by author* Check by user nicename and ID*/$curauth = get_userdata($wp_query->post->post_author);if(file_exists(SINGLE_PATH . '/single-author-' . $curauth->user_nicename . '.php'))return SINGLE_PATH . '/single-author-' . $curauth->user_nicename . '.php';elseif(file_exists(SINGLE_PATH . '/single-author-' . $curauth->ID . '.php'))return SINGLE_PATH . '/single-author-' . $curauth->ID . '.php';} |