在构建大型网站时,通常会有上百个栏目。为了优化SEO效果,在栏目模板中,我们通常会使用以下代码来调用栏目标题、关键字和描述。


<title>{dede:field.seotitle/}</title>
<meta name="keywords" content="{dede:field name='keywords'/}" />
<meta name="description" content="{dede:field name='description' function='html2text(@me)'/}" />

然而,这种方法存在一个问题:如果某些栏目忘记填写标题、关键字或描述,那么这些字段将会为空。为了解决这个问题,我们可以设置当栏目标题、关键字或描述为空时,自动调用上级栏目的内容;若上级栏目也为空,则继续调用上上级栏目,直到顶级栏目。如果顶级栏目仍然没有内容,则调用网站首页的标题、关键字和描述。

接下来,我将分享一种实现该功能的方法。

### 第一步:修改核心文件
打开`/include/typelink.class.php`文件,找到如下代码:


$this->TypeInfos = $this->dsql->GetOne($query);

在其下方添加以下三行代码:


$this->TypeInfos['keywords'] = $this->TypeInfos['keywords'] ? $this->TypeInfos['keywords'] : $this->GetTrueInfos('keywords');
$this->TypeInfos['seotitle'] = $this->TypeInfos['seotitle'] ? $this->TypeInfos['seotitle'] : $this->GetTrueInfos('seotitle');
$this->TypeInfos['description'] = $this->TypeInfos['description'] ? $this->TypeInfos['description'] : $this->GetTrueInfos('description');

完整的代码段应如下所示:


$query = "SELECT tp.*,ch.typename as ctypename,ch.addtable,ch.issystem FROM `idea_arctype` tp left join `idea_channeltype` ch
on ch.id=tp.channeltype  WHERE tp.id='$typeid' ";
if($typeid > 0)
{
    $this->TypeInfos = $this->dsql->GetOne($query);

    // 填充空值
    $this->TypeInfos['keywords'] = $this->TypeInfos['keywords'] ? $this->TypeInfos['keywords'] : $this->GetTrueInfos('keywords');
    $this->TypeInfos['seotitle'] = $this->TypeInfos['seotitle'] ? $this->TypeInfos['seotitle'] : $this->GetTrueInfos('seotitle');
    $this->TypeInfos['description'] = $this->TypeInfos['description'] ? $this->TypeInfos['description'] : $this->GetTrueInfos('description');

    if(is_array($this->TypeInfos))
    {
        $this->TypeInfos['tempindex'] = MfTemplet($this->TypeInfos['tempindex']);
        $this->TypeInfos['templist'] = MfTemplet($this->TypeInfos['templist']);
        $this->TypeInfos['temparticle'] = MfTemplet($this->TypeInfos['temparticle']);
    }
}


### 第二步:添加自定义方法
在`TypeLink`类中增加一个名为`GetTrueInfos`的方法,用于递归获取上级栏目的信息。代码如下:


function GetTrueInfos($info = 'seotitle') {
    $infos = array('reid'=>$this->TypeID,$info=>'');
    while(empty($infos[$info]) && $infos['reid']!=0) {
        $this->dsql->SetQuery("SELECT reid,".$info." FROM idea_arctype WHERE id='".$infos['reid']."'");
        $infos = $this->dsql->GetOne();
    }
    if(empty($infos[$info])) {
        if($info == "seotitle") return $GLOBALS['cfg_webname'];
        if($info == "keywords") return $GLOBALS['cfg_keywords'];
        if($info == "description") return $GLOBALS['cfg_description'];
    }
    return $infos[$info];
}


### 保存并测试
完成上述修改后,生成静态页面并预览效果。此方法已在DEDECMS 5.7 SP1版本上测试通过,其他版本可能需要进一步验证。

通过以上步骤,您可以确保每个栏目都能拥有有效的SEO标题、关键字和描述,从而提升网站的整体搜索引擎优化效果。希望这个方法对您有所帮助!