博客 / WordPress 教程

如何通过判断实现不同层级页面的布局模板输出?

如果不同页面的模板风格是有规律的,比如不同层级的网页设计风格不一样,那么通过 WordPress 的页面层级 (page hierarchy) 来判断不同层级并应用不同的布局结构,而不需要依赖具体的页面 ID。下面是一个示例展示如何在 page.php 中基于页面层级来应用不同的 HTML DOM 结构。

<?php
// 获取当前页面的对象
$current_page = get_queried_object();

// 检查页面是否有父级页面
if ($current_page->post_parent == 0) {
    // 顶级页面 (Level 1)
    ?>
    <div class="layout-level-1">
        <h1><?php echo get_the_title(); ?></h1>
        <p>这是 Level 1 的布局。</p>
    </div>
    <?php
} elseif ($current_page->post_parent != 0) {
    // 获取当前页面的所有祖先
    $ancestors = get_post_ancestors($current_page->ID);
    
    // 根据祖先数量判断层级
    if (count($ancestors) == 1) {
        // 二级页面 (Level 2)
        ?>
        <div class="layout-level-2">
            <h2><?php echo get_the_title(); ?></h2>
            <p>这是 Level 2 的布局。</p>
        </div>
        <?php
    } elseif (count($ancestors) == 2) {
        // 三级页面 (Level 3)
        ?>
        <div class="layout-level-3">
            <h3><?php echo get_the_title(); ?></h3>
            <p>这是 Level 3 的布局。</p>
        </div>
        <?php
    } elseif (count($ancestors) == 3) {
        // 四级页面 (Level 4)
        ?>
        <div class="layout-level-4">
            <h4><?php echo get_the_title(); ?></h4>
            <p>这是 Level 4 的布局。</p>
        </div>
        <?php
    }
}

// 正文内容
the_content();
?>

代码解析:

  1. get_queried_object() 获取当前页面的对象。
  2. post_parent 判断当前页面是否有父级页面:
    • post_parent == 0 表示顶级页面 (Level 1)。
    • 如果有父级页面,通过 get_post_ancestors() 获取页面的祖先页面。
  3. get_post_ancestors() 返回一个数组,表示当前页面的所有祖先页面:
    • count($ancestors) == 1 表示二级页面 (Level 2)。
    • count($ancestors) == 2 表示三级页面 (Level 3)。

布局:

根据页面层级不同,Level 1Level 2Level 3 可以使用不同的 HTML 结构来展示页面内容。

这种方式比依赖页面 ID 更灵活,并且适用于页面层级的动态变化。

评论留言

您的邮箱地址不会被公开。 必填项已用 * 标注