純 PHP 程式碼產生 xml 站點地圖
4,064 0
站點地圖可以方便網站管理員告訴搜尋引擎他的網站上有哪些可供抓取的網頁連結。最簡單的站點地圖形式,就是 sitemap.xml 檔案,其中列出網站中的網址以及關於每個網址的其他中繼資料(如上次更新的時間、更改的頻率以及相對於網站上其他網址的重要程度),以便搜尋引擎可以更加智慧地抓取網站。
對於 WordPress 產生 sitemap.xml 地圖,國內已經有人撰寫了專門的外掛,例如較為知名的柳城的 Baidu Sitemap Generator,國外的有 Google XML Sitemaps。
不過,我覺得僅僅為了產生一個 sitemap.xml 檔案就使用外掛會顯得有點浪費資源,所以就用程式碼實作吧!程式碼是從網路上找到的,我稍作修改後,支援產生標籤和分類的 XML,並增加了 sitemap.xml 產生時間。
PHP 程式碼
新建一個 sitemap.php 檔案,將以下程式碼寫入該檔案:
PHP PHP
<?php
require('./wp-blog-header.php');
header("Content-type: text/xml");
header('HTTP/1.1 200 OK');
$posts_to_show = 1000;
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">';
?>
<!-- 生成时间 <?php echo $showtime = date("Y-m-d H:i:s"); ?> -->
<url>
<loc><?php echo get_home_url(); ?></loc>
<lastmod><?php $ltime = get_lastpostmodified(GMT); $ltime = gmdate('Y-m-d\TH:i:s+00:00', strtotime($ltime)); echo $ltime; ?></lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<?php
// 文章
$myposts = get_posts("numberposts=" . $posts_to_show);
foreach ($myposts as $post) { ?>
<url>
<loc><?php the_permalink(); ?></loc>
<lastmod><?php the_time('c'); ?></lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<?php } ?>
<?php
// 页面
$mypages = get_pages();
if (count($mypages) > 0) {
foreach ($mypages as $page) { ?>
<url>
<loc><?php echo get_page_link($page->ID); ?></loc>
<lastmod><?php echo str_replace(" ", "T", get_page($page->ID)->post_modified); ?>+00:00</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<?php }} ?>
<?php
// 分类
$terms = get_terms('category', 'orderby=name&hide_empty=0');
$count = count($terms);
if ($count > 0) {
foreach ($terms as $term) { ?>
<url>
<loc><?php echo get_term_link($term, $term->slug); ?></loc>
<changefreq>weekly</changefreq>
<priority>0.4</priority>
</url>
<?php }} ?>
<?php
// 标签
$tags = get_terms("post_tag");
foreach ($tags as $key => $tag) {
$link = get_term_link(intval($tag->term_id), "post_tag");
if (is_wp_error($link)) return false;
$tags[$key]->link = $link;
?>
<url>
<loc><?php echo $link; ?></loc>
<changefreq>weekly</changefreq>
<priority>0.2</priority>
</url>
<?php } ?>
</urlset>
將 sitemap.php 上傳到網站根目錄,然後造訪查看效果。
偽靜態方案
Nginx
編輯已存在的 Nginx 偽靜態規則,新增如下規則後重新啟動 Nginx 即可:
Nginx Nginx
rewrite ^/sitemap.xml$ /sitemap.php last;
Apache
編輯網站根目錄的 .htaccess 檔案,加入如下規則:
Apache Apache
RewriteRule ^(sitemap)\.xml$ $1.php
純靜態方案
Linux 排程任務 + wget 定時產生 sitemap.xml(該方案適合 VPS 使用者,不適用於虛擬主機)
將網站根目錄的 sitemap.php 重新命名為一個只有自己知道的 PHP 檔案,例如 xml.php。
然後用 Linux 排程任務執行以下命令,將資料儲存為 sitemap.xml,存放到網站根目錄即可:
Bash Bash
wget -O /home/www/www.ikxin.com/sitemap.xml https://www.ikxin.com/sitemap.php
https://www.ikxin.com/sitemap.php是 PHP 的路徑。/home/www/www.ikxin.com/sitemap.xml是 XML 檔案存放路徑。
這樣一來,就解決了 sitemap.xml 是動態資料的問題了。

評論
(0)暫無評論,來說兩句吧