大网数据广告活动
网站运营与故障问答

SEO method to set page titles differently? (same header PHP)

· 52CE 我爱测

My PHP-based site files start off with <?php include("PHP/header.php"); ?> which includes all the HTML (metadata, scripts, etc.) shared by every page - along <head> and <title> . The options I've considered for dynamic page title…

问题原文

原帖链接 · OverLordGoldDragon · CC BY-SA 4.0

My PHP-based site files start off with

<?php include("PHP/header.php"); ?>

which includes all the HTML (metadata, scripts, etc.) shared by every page - along <head> and <title>. The options I've considered for dynamic page titles are:

<title id="title">...</title>
...
<script>window.onload=function(){document.getElementById('title').innerHTML="New title"}
</script>

and

<?php include("PHP/header1.php"); ?> <!-- code in header.php before <title> -->
<title>New title</title>
<?php include("PHP/header2.php"); ?> <!-- code after </title> -->

(I intend the same for page descriptions - omitted for brevity.)

Which of these is preferable for search engine optimization - do better approaches exist? Lastly, any performance differences to note (scripts vs. php, etc)?

已采纳解答

原帖链接 · Stephen Ostermiller · CC BY-SA 4.0

Set the title as a variable and pass it to your include:

<?php 
    $page_title = 'Welcome to my site';
    include("PHP/header.php");
?>

Then inside your header PHP you can use that variable. Here I'm using htmlspecialchars to ensure that <>& are properly escaped if they are used in the title.

<title><?php echo htmlspecialchars($page_title); ?></title>

You could even put code in your header PHP to check that the title has been set and to use a default title if it hasn't been:

if (empty($page_title)) {
    $page_title = 'This page gets this default title';
}

You could use the same technique for other items that you might want to customize in the header such as the meta description.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2018-11-14)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。