为wordpress顶部header.php文件中调用不同的标题和摘要

发布于:2025-08-11 ⋅ 阅读:(14) ⋅ 点赞:(0)

wordpress顶部header.php文件中调用网站标题和摘要,当在首页时,网站标题不加链接,调用网站摘要,当在首页以外的其它页时,给网站标题加链接,当在分类页里,调用分类描述,当在post页和page页时,调用post的摘要,page的摘要。

在 WordPress 的 header.php 文件中,可以通过条件判断来实现你描述的功能。以下是一个示例代码,你可以根据自己的需求进行调整:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php wp_title('|', true, 'right'); ?></title>
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<header>
    <div class="site-branding">
        <?php
        if (is_home() || is_front_page()) {
            // 首页时,显示网站标题和网站摘要,不加链接
            bloginfo('name'); // 显示网站标题
            echo '<p>' . get_bloginfo('description') . '</p>'; // 显示网站摘要
        } elseif (is_category()) {
            // 分类页时,显示分类描述
            $category = get_queried_object();
            echo '<h1>' . single_cat_title('', false) . '</h1>'; // 显示分类名称
            echo '<p>' . category_description() . '</p>'; // 显示分类描述
        } elseif (is_single()) {
            // 文章页时,显示文章摘要
            echo '<h1>' . get_the_title() . '</h1>'; // 显示文章标题
            echo '<p>' . get_the_excerpt() . '</p>'; // 显示文章摘要
        } elseif (is_page()) {
            // 页面时,显示页面摘要
            echo '<h1>' . get_the_title() . '</h1>'; // 显示页面标题
            echo '<p>' . get_the_excerpt() . '</p>'; // 显示页面摘要
        } else {
            // 其他页面,显示网站标题并加链接
            echo '<a href="' . home_url('/') . '">' . bloginfo('name') . '</a>';
        }
        ?>
    </div>
</header>
<?php

代码说明:

首页(is_home() 或 is_front_page()):

显示网站标题(bloginfo(‘name’))和网站摘要(get_bloginfo(‘description’)),不加链接。

分类页(is_category()):

显示分类名称(single_cat_title())和分类描述(category_description())。

文章页(is_single()):

显示文章标题(get_the_title())和文章摘要(get_the_excerpt())。

页面(is_page()):

显示页面标题(get_the_title())和页面摘要(get_the_excerpt())。

其他页面:

显示网站标题并加链接(home_url(‘/’))。

注意事项:

确保你的主题支持摘要功能(get_the_excerpt()),否则可能需要手动添加摘要。

如果你的主题有自定义的标题或描述字段,可能需要调整代码以适配这些字段。

在实际使用中,可以根据需要调整 HTML 结构和样式。

将以上代码替换到你的 header.php 文件中相应的位置即可实现功能。

原文

http://www.wordpress.sd.cn/jianzhan/72.html