2017年12月11日 星期一

wordpres免插件带分页sitemap

Tech An 1133阅读 0评论

有个站点数据量比较大,wordpress sitemap插件都是全量生成,蜘蛛请求的时候会超时,于是简单撸了个带分页的版本。命名为sitemap.php放到根目录即可

<?php
/**
 * sitemap.php
 * @author: qiananhua
 * @date: 2017/8/17
 */

require './wp-blog-header.php';
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;

class SiteMap {
   private $wp_post_count;
   private $totalPage;
   private $everPageNum;

   public function __construct( $everPage ) {
      $this->wp_post_count = wp_count_posts();
      $this->everPageNum   = $everPage;
      $this->totalPage     = ceil( $this->wp_post_count->publish / $this->everPageNum );
   }

   public function index() {
      echo '<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
      for ( $page = 1; $page <= $this->totalPage; $page ++ ) { ?>
            <sitemap>
                <loc><?php echo get_home_url() ?>/sitemap.php?page=<?php echo $page ?></loc>
                <lastmod><?php echo gmdate( 'Y-m-d\TH:i:s+00:00', strtotime( get_lastpostmodified( 'GMT' ) ) ) ?></lastmod>
            </sitemap>
      <?php }
      echo '</sitemapindex>';
   }

   public function post( $page ) {
      if ( $page > $this->totalPage ) {
         die('fuck');
      }

      $postList = get_posts( [
         'numberposts' => $this->everPageNum,
         'offset'      => $page == 1 ? 0 : ( $page - 1 ) * $this->everPageNum
      ] );

      echo '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
      foreach ( $postList as $post ) { ?>
            <url>
                <loc><?php echo get_permalink( $post->ID ) ?></loc>
                <lastmod><?php echo gmdate( 'Y-m-d\TH:i:s+00:00', strtotime( $post->post_modified_gmt ) ) ?></lastmod>
                <changefreq>monthly</changefreq>
                <priority>0.6</priority>
            </url>
      <?php }
      echo '</urlset>';
      return;
   }

}

header( 'Content-type: text/xml' );
header( 'HTTP/1.1 200 OK' );

$everPage = 1000;
$page     = ! empty( $_REQUEST['page'] ) ? $_REQUEST['page'] : '';
$siteMap  = new SiteMap( $everPage );

if ( empty( $page ) ) {
   $siteMap->index();
} else {
   $siteMap->post( $page );
}
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址