WordPress免插件生成完整站點地圖(sitemap.xml)的php代碼


讓這個代碼更加完善,可以同時生成首頁、文章、單頁面、分類和標簽的 sitemap!

一、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/">'
?>
<!-- generated-on=<?php echo get_lastpostdate('blog'); ?> Diy By 張戈博客(http://zhangge.net)-->
  <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>monthly</changefreq>
      <priority>0.6</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.8</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>monthly</changefreq>
      <priority>0.4</priority>
  </url>
<?php  } /* 標簽循環結束 */ ?> 
</urlset>

三、純靜態

Linux 定時任務+wget 定時生成 sitemap.xml

具體實現:將 sitemap.php 放到某個不為人知的目錄,然后定時使用 wget 去請求這個文件,並將數據保存為 sitemap.xml 存放到網站根目錄就可以了!比如:

如果是啟用了 https 的站點,需要加入 --no-check-certificate  的選項

#每天在網站根目錄生成一個sitemap.xml diypath為sitemap.php的實際位置(針對https網站)
0 1 * * * wget -O /home/wwwroot/zhangge.net/sitemap.xml --no-check-certificate https://zhangge.net/diypath/sitemap.php  >/dev/null 2>&1

 

0 1 * * * wget https://zhangge.net/diypath/sitemap.php  -O /home/wwwroot/zhangge.net/sitemap.xml --no-check-certificate  >/dev/null 2>&1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM