在网站建设中,通过标签(tag)调用相关文章是一种常见的需求。虽然帝国官方论坛上曾有人分享过类似的方法,但这些方法往往存在效率低下或参数设置不够灵活的问题。东坡网采用了一种更为高效且实用的方案,利用自定义函数实现了基于标签的相关文章调用。
一、 自定义函数实现
首先需要创建一个自定义函数 user_OtherLink,并将其添加到 eclassuserfun.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 = array();
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 (array_search($myprint, $isprint) !== false) {
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 += 1;
if ($i >= $num) {
break;
}
}
}
$keyboardtext = $temp_r[0] . $str . $temp_r[2];
if ($str) {
return $keyboardtext;
} else {
return '暂无相关信息';
}
}
二、 使用方法
该函数的调用方式非常简单,其格式为:user_OtherLink(调用条数,指定栏目id,指定模型id)。
需要注意的是,相关文章的模板采用了公共模板中的“相关信息模板”。以下是一个具体的调用示例:
<?=user_OtherLink(10, 0, 1)?>
上述代码表示从当前文章的标签中查找最多10篇相关文章,不限定栏目ID,但限定模型ID为1。
三、 总结
通过这种方式,您可以轻松地在网站中实现基于标签的相关文章推荐功能。这种方法不仅提高了查询效率,还提供了更加灵活的参数设置选项,使开发者能够根据实际需求进行调整。对于希望优化用户体验、提升内容关联性的网站来说,这无疑是一个值得尝试的解决方案。