微信关注,获取新知

WordPress创建自定义Page模板文件

默认的WordPress页面文件的模板是page.php,我们也可以根据需要去自定义模版,然后在模版中选择。

在主题目录下新建 template-custom.php(自己取名字) 文件,添加以下代码:

/*
Template Name: 单页面page名称
Template Post Type: page
*/

这个头部很重要,我们只要标识好后在创建page页面的时候右侧页面模板还可以有选择。这样我们只需要选择即可。示范:

<?php
/*
Template Name: 全宽布局模板
Template Post Type: page
*/
get_header(); ?>

<div class="custom-page-container">
    <!-- 自定义页头 -->
    <header class="custom-page-header" style="background: url(<?php echo get_the_post_thumbnail_url(); ?>)">
        <h1><?php the_title(); ?></h1>
        <?php if(get_field('subtitle')): ?>
            <p class="subtitle"><?php the_field('subtitle'); ?></p>
        <?php endif; ?>
    </header>

    <!-- 主内容区 -->
    <main class="custom-page-content">
        <?php 
        while (have_posts()) : the_post();
            the_content();
        endwhile;
        ?>
    </main>

    <!-- 可选侧边栏 -->
    <?php if(is_active_sidebar('custom-page-widget')) : ?>
        <aside class="custom-sidebar">
            <?php dynamic_sidebar('custom-page-widget'); ?>
        </aside>
    <?php endif; ?>
</div>

<?php get_footer(); ?>

如果我们有需要定义的样式也可以单独丢到对应的CSS中。

/* 全宽布局 */
.custom-page-container {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    gap: 30px;
}

.custom-page-header {
    height: 400px;
    background-size: cover !important;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    text-align: center;
    margin-bottom: 50px;
}

.custom-page-content {
    flex: 3;
    padding: 20px;
}

.custom-sidebar {
    flex: 1;
    background: #f5f5f5;
    padding: 20px;
}

.subtitle {
    font-size: 1.2em;
    opacity: 0.8;
}

 

投上你的一票

未经允许不得转载:老蒋玩运营 » WordPress创建自定义Page模板文件