Discuz X3.4免插件定时自动生成sitemap.xml方法
如何使用定时任务在Discuz X3.4中免插件自动生成sitemap.xml
了更好的利于SEO,加快百度、360、谷歌、bing、搜狗等收录,我们需要网站生成sitemap.xml,有些搜索引擎只支持.xml,不支持.txt,所以我们必须在511遇见论坛下自动生成sitemap.xml,由于我们采用了伪静态,所以生成的链接必须和伪静态规则一致,在discuz后台插件搜索了几个,姑且不谈收费免费,发现很不稳定,且静态规则无法兼容,这里我们采用discuz的定时任务,自动生成sitemap.xml。
手动建立一个cron_sitemap.php文件复制以下内容:
<?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$filename='sitemap.xml';
//以下五项根据具体情况修改即可
$cfg_updateperi='60';//协议文件更新周期的上限,单位为分钟
$web_root=$_G['siteurl'];//根网址
$CHARSET='utf-8';// or gbk //选择编码方式
/***********************************************************************************************/
//网站地图sitemap.xml
$sitemap="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$sitemap.="<urlset\n";
$sitemap.="xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n";
$sitemap.="xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
$sitemap.="xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n";
$sitemap.="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n";
$querys = DB::query("SELECT a.tid FROM ".DB::table('forum_thread')." a inner join ".DB::table('forum_forum')." b on a.fid=b.fid ORDER BY a.tid DESC LIMIT 0,10000");
while($threadfid = DB::fetch($querys))
{
$turl=$web_root.'thread-'.$threadfid['tid'].'-1-1.html';//注意静态规则
$link = $turl;
$t=time();
$riqi=date("Y-m-d",$t);
$priority=rand(1,10)/10;
//date("D F d Y",$t);
$sitemap.="<url>\n";
$sitemap.="<loc>$link</loc>\n";
$sitemap.="<priority>$priority</priority>\n";
$sitemap.="<lastmod>$riqi</lastmod>\n";
$sitemap.="<changefreq>weekly</changefreq>\n";
$sitemap.="</url>\n";
}
$sitemap .= "</urlset>\n";
$fp = fopen(DISCUZ_ROOT.'/'.$filename,'w');
fwrite($fp,$sitemap);
fclose($fp);
?>
1. 检查定义常量:
代码首先检查是否定义了常量 IN_DISCUZ,如果没有定义,则直接退出并显示 "Access Denied"。
2. 定义变量:
定义了文件名 $filename 为 'sitemap.xml'。
定义了更新周期 $cfg_updateperi 为 '60' 分钟。
定义了网站根网址 $web_root 为 $_G['siteurl']。
定义了字符编码 $CHARSET 为 'utf-8'(也可以是 'gbk')。
3. 生成 sitemap.xml 内容:
初始化 $sitemap 变量,写入 XML 声明和 urlset 标签的开始部分,包括命名空间和模式位置。
4. 数据库查询:
使用 DB::query 查询 forum_thread 表和 forum_forum 表,获取最新的 10000 个帖子的 tid,并按 tid 降序排列。
5. 生成 URL 条目:
对于每个查询结果,生成帖子的 URL $turl,格式为 $web_root.'thread-'.$threadfid['tid'].'-1-1.html'。
设置链接 $link 为生成的 URL。
获取当前时间 $t 和日期 $riqi。
生成随机优先级 $priority,范围为 0.1 到 1.0。
将每个 URL 的 <url> 标签及其子标签(<loc>、<priority>、<lastmod>、<changefreq>)写入 $sitemap。
6. 保存文件:
将 $sitemap 内容写入到 DISCUZ_ROOT.'/'.$filename 文件中。


声明:本文由"百度是最好的搜索"发布,不代表"破站"立场,转载联系作者并注明出处:https://www.848586.cn/204975.html
