如何在包含文件中设置默认(或更改)元描述

How to set default (or change) meta description in include file

我有网页 example.org,其中有多个子类别,例如:

并且我在 index.php 中包含了 head.php 文件,其中包含:

if(!empty($settings->meta_description) && (!isset($_GET['page']) || (isset($_GET['page']) && $_GET['page'] != 'category')))
    echo '<meta name="description" content="' . $settings->meta_description . '" />';
elseif(isset($_GET['page']) && $_GET['page'] == 'category' && !empty($category->description))
    echo '<meta name="description" content="' . $category->description . '" />';

是否可以为所有页​​面(子类别)设置默认元描述?或者如何手动写所有页面的描述(大约25页,所以我可以手动写,但是怎么做?)

因为用户可以添加页面,所以我需要设置默认元描述(因为我不想要重复的元描述)

有解决办法吗?对不起我的英语。

有点重新发明轮子,但出于学习目的,以下内容对您有意义吗?老实说,您应该看看一些 MVC 框架是如何处理这个问题的。

<?php
$pageData = [
    'category'  => ['title' => 'This is a title', 'description' => 'Hello world...'],
    'login'     => ['title' => 'This is a title', 'description' => 'Hello world...'],
    'names'     => ['title' => 'This is a title', 'description' => 'Hello world...'],
]


if (isset($_GET['page']) {
    if (isset($pageData[$_GET['page'])) {   
        //we have defined meta data specific for this page                  
        echo '<meta name="description" content="' . $pageData[$_GET['page']['description'] . '" />';            
    } else {
        //page paramter was passsed but no specific values assigned for the page
        echo '<meta name="description" content="This is some default/fallback text." />';
    }
} else {
    //page paramter not passsed in
    echo '<meta name="description" content="This is some other default/fallback text." />';
}

实际上,执行此操作的最佳方法是设置一个数据库 table,其中包含一个 name 列和一个 description 列。然后你可以像这样检查每个页面的描述(这个例子使用mysql语法)

$result = $mysql->query("SELECT description FROM pageinfo WHERE page = '" 
    . $mysql->escape_string($_GET['page']) . "'");
if($result->num_rows){
    $description = $result->fetch_array()[0];
} else {
    $description = 'Default description...';
}
#echo the description here...


但是,如果你不想使用数据库或者不想学习语法,你可以使用纯 PHP 来完成:
您可以使用切换块来检查您所在的页面,然后根据页面设置描述($desc 将是本示例中的页面描述)。

#use a switch block to check what page the user is on
$desc = '';
switch($_GET['page']){
    case 'login':
        $desc = 'Login page description';
        break; #make sure you include the break statement
    case 'category':
        $desc = 'Category description';
        break;

    #( include the rest of the page names )

    default:
        #this will happen if none of the other conditions are met
        $desc = 'Default description';
        break;
}

这是来自 php.netswitch block 的一些信息:

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to.