萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> CMS 教學

帝國CMS 利用 TAG 調用相關文章:自定義函數 user_OtherLink 完整實現與調用示例

核心思路

利用帝國CMS 內建 TAG 系統(phome_enewstags, phome_enewstagsdata),通過當前文章的 TAG 查找同標簽文章,排除自身,支持限定欄目/模型/數量,採用公共模板「相關信息模板」渲染。

步驟一:添加自定義函數

編輯 e/class/userfun.php,在 ?> 前插入:

<?php
// 根據 TAG 獲取相關信息
function user_OtherLink($num, $classid = 0, $mid = 0) {
    global $dbtbpre, $empire, $navinfor, $class_r;

    if (empty($navinfor['infotags'])) {
        return '暫無相關信息';
    }
    // 限定模型時需校驗欄目屬於該模型
    if ($mid && $classid && $class_r[$classid]['modid'] != $mid) {
        return '暫無相關信息';
    }

    // 讀取公共模板:相關信息模板
    $tr = $empire->fetch1("SELECT otherlinktemp, otherlinktempsub, otherlinktempdate FROM " . GetTemptb("enewspubtemp") . " LIMIT 1");
    $temp_r = explode("[!--empirenews.listtemp--]", $tr['otherlinktemp']);

    $str = '';
    $tagsql = $empire->query("SELECT * FROM {$dbtbpre}enewstagsdata WHERE id='$navinfor[id]' AND classid='$navinfor[classid]'");
    $i = 0;
    $isprint = [];

    while ($tagr = $empire->fetch($tagsql)) {
        if ($i >= $num) break;
        $gsql = $empire->query("SELECT * FROM {$dbtbpre}enewstagsdata WHERE tagid='$tagr[tagid]'");
        while ($gr = $empire->fetch($gsql)) {
            $myprint = 'id' . $gr['id'] . 'class' . $gr['classid'];
            if (in_array($myprint, $isprint)) continue;
            $isprint[] = $myprint;

            if ($classid && $classid != $gr['classid']) continue;
            if ($mid && $mid != $gr['mid']) continue;
            if ($gr['id'] == $navinfor['id'] && $gr['classid'] == $navinfor['classid']) continue;

            $tbname = $class_r[$gr['classid']]['tbname'];
            if (!$tbname || !InfoIsInTable($tbname)) continue;

            $r = $empire->fetch1("SELECT * FROM {$dbtbpre}ecms_{$tbname} WHERE id='$gr[id]' LIMIT 1");
            if (!$r['id']) continue;

            $str .= RepOtherTemp($temp_r[1], $r, $tr);
            $i++;
            if ($i >= $num) break;
        }
    }

    if ($str) {
        return $temp_r[0] . $str . $temp_r[2];
    } else {
        return '暫無相關信息';
    }
}
?>

步驟二:模板中調用

在內容模板(或靈動標籤中)任意位置寫入:

<?=user_OtherLink(10, 0, 1)?>

參數說明:

  • $num:調用條數(示例 10 條)。
  • $classid:限定欄目 ID,0 為不限制。
  • $mid:限定模型 ID(1=新聞, 2=文章…),0 為不限制。

模板配置

後台 → 模板 → 公共模板 → **相關信息模板** 設計列表樣式,可用標籤:[!--title--], [!--titleurl--], [!--newstime--] 等。

優化建議

  • 大數據量時,TAG 表需加索引:ALTER TABLE phome_enewstagsdata ADD INDEX idx_tagid_classid (tagid, classid);
  • 緩存結果:將函數返回值存入臨時表/Redis,定時刷新,減少即時查詢壓力。
  • 若需按 TAG 權重排序,需擴展 TAG 權重字段並修改查詢 ORDER BY。
copyright © 萬盛學電腦網 all rights reserved