wordpress怎么设置多个模板
时间 : 2023-11-28 10:12:01声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案
在WordPress中设置多个模板需要进行以下几个步骤:
1. 创建模板文件:首先,你需要创建多个模板文件,这些文件将用于不同的页面或文章类型。可以在主题文件夹中创建一个新的文件夹,用来存放这些模板文件。
2. 修改主题文件:打开主题文件夹,找到`functions.php`文件。在文件中添加以下代码来注册模板文件:
```php
function custom_template_register() {
$templates = array(
'template-one.php' => 'Template One',
'template-two.php' => 'Template Two'
);
foreach ( $templates as $filename => $name ) {
$file = get_stylesheet_directory() . '/templates/' . $filename;
$template = $filename;
if ( file_exists( $file ) ) {
add_post_type_support( 'page', 'custom-template' );
$data = get_file_data( $file, array( 'Template Name' => 'Template Name' ) );
$name = ! empty( $data['Template Name'] ) ? $data['Template Name'] : $name;
$post_type_object = get_post_type_object( 'page' );
$post_type_object->template = $template;
$post_type_object->template_name = $name;
}
}
}
add_action( 'init', 'custom_template_register' );
上述代码中,`$templates`是一个关联数组,其中键表示模板文件名,值表示模板的显示名称。你可以根据自己的需求添加多个模板。
3. 创建模板文件内容:在模板文件夹中创建对应的模板文件,例如`template-one.php`和`template-two.php`。在这些文件中编写你想要显示的内容和布局。
4. 应用模板:在编辑页面或文章时,在右侧边栏中找到“页面模板”选项。选择你想要应用的模板,保存页面或文章。
通过以上步骤,你就成功设置了多个模板。现在,你可以为不同的页面或文章类型选择不同的模板来定制它们的显示效果。
其他答案
在WordPress中,设置多个模板需要以下步骤:
1. 首先,在你的主题文件夹中,创建一个新的模板文件。你可以复制主题文件夹中的现有模板文件,并进行相应的修改,或者创建一个新的模板文件。新的模板文件的命名应该与你希望设置的页面或文章类型相关联,例如,如果你要创建一个单独的模板用于特定的文章类型(比如产品介绍),可以将这个模板命名为"single-product.php"。
2. 编辑新的模板文件,并添加你希望显示的内容和布局。你可以使用HTML和PHP来创建模板文件。你可以自定义模板的标题、导航菜单、侧边栏、文章内容和页脚等部分。
3. 保存并上传你的新模板文件到主题文件夹中。
4. 在WordPress后台,进入"外观" -> "编辑"页面。找到主题文件夹中的"functions.php"文件,并点击编辑。如果你的主题没有"functions.php"文件,可以在主题文件夹中创建一个新的。
5. 在"functions.php"文件中,添加以下代码来注册你的新模板:
function custom_template_include($template) {
global $post;
if ($post->post_type == 'your_custom_post_type') { //替换 'your_custom_post_type' 为你自定义文章类型的名称
copy(get_stylesheet_directory() . '/your_custom_template.php', $template); //替换 'your_custom_template.php' 为你创建的新模板文件的名称
}
return $template;
}
add_filter('template_include', 'custom_template_include');
替换代码中的'your_custom_post_type'为你希望使用新模板的自定义文章类型的名称,替换'your_custom_template.php'为你创建的新模板文件的名称。
6. 保存并上传你的"functions.php"文件到主题文件夹中。
现在,你已经成功设置了一个新的模板。在你的WordPress后台,当你创建一个新的文章或页面,并选择使用自定义文章类型时,你可以选择使用你刚刚创建的新模板。
重复以上步骤,你可以设置多个不同的模板,以适应不同的页面和文章类型。
https/SSL证书广告优选IDC>>
推荐主题模板更多>>
推荐文章