WordPress生成xml

文章描述:

Wordpress生成xml文件sitemap.xml是为了搜索引擎更快的收录网站,那么WordPress如何生成xml呢?

读取数据库

首先调用数据库类对已发布的文章进行查询,把查询到的结果打印出来。

<?php
global $wpdb;
$wpdb->show_errors();//开启提示
 
$post_status = 'publish';
$post_type = 'post';
 
$items = $wpdb->get_results("SELECT ID,post_title FROM ".$wpdb->prefix."posts WHERE post_status='$post_status' AND post_type='$post_type' ORDER BY ID DESC LIMIT 0,5000",ARRAY_A);
 
echo "<pre>";
print_r($items);
echo "</pre>";
exit;

创建生成xml

首先要创建xml对象,然后把数据循环到xml内部然后生成sitemap.xml文件。

$self=$_SERVER['HTTP_REFERER'];
$u=$_SERVER['HTTP_HOST'];
$url="https://"."$u";
$date_time=date("Y-m-d H:i:s");
$dom = new DomDocument('1.0','utf-8'); //创建DOM对象
 
$object = $dom->createElement('urlset'); //创建根节点rss
$dom->appendChild($object); //将创建的根节点添加到dom对象中
//$type1 = $dom->createAttribute('xmlns'); //创建一个节点属性xmlns:rdf
//$object->appendChild($type1); //将属性追加到rss根节点中
//$type1_value = $dom->createTextNode('http://www.sitemaps.org/schemas/sitemap/0.9'); //创建一个属性值
//$type1->appendChild($type1_value); //将属性值赋给属性xmlns:rdf
 
foreach($items as $myrow){
 
$item = $dom->createElement('url'); //创建节点item
$object->appendChild($item); //将item追加到channel节点下
 
$item_link = $dom->createElement('loc'); //创建link节点
$item->appendChild($item_link); //将节点追加到item节点下
 
$item_pubDate = $dom->createElement('lastmod'); //创建节点pubDate
$item->appendChild($item_pubDate); //将节点追加到item节点下
 
$item_changefreq = $dom->createElement('changefreq'); //创建description节点
$item->appendChild($item_changefreq); //将节点追加到item节点中
 
$item_priority = $dom->createElement('priority'); //创建description节点
$item->appendChild($item_priority); //将节点追加到item节点中
//----------------------
 
$link_value = $dom->createTextNode(iconv('gb2312','utf-8',get_the_permalink($myrow['ID'])));//创建元素值
$item_link->appendChild($link_value); //将值赋给link节点
 
$pubDate_value = $dom->createTextNode(iconv('gb2312','utf-8',substr($myrow['post_modified'],2,8)));//创建元素值
$item_pubDate->appendChild($pubDate_value); //将值赋给pubDate节点
 
$changefreq_valeu = $dom->createTextNode(iconv('gb2312','utf-8',"daily"));//创建元素值
$item_changefreq->appendChild($changefreq_valeu);
 
$priority_valeu = $dom->createTextNode(iconv('gb2312','utf-8',"0.8"));//创建元素值
$item_priority->appendChild($priority_valeu);
 
//echo get_the_permalink($myrow[ID])."<br/>";
}
//exit;
 
$modi = $dom->saveXML(); //生成xml文档
file_put_contents('sitemap.xml',$modi); /* 将对象保存到Rss.xml文档中 */

 

发布时间:2021/08/10

发表评论