久久久精品2019免费观看_亚洲国产精品成人久久久_69国产成人综合久久精品91_国产精品久久精品视

WordPress定時生成Sitemap XML地圖(非插件)

只用WordPress定時任務去生成sitemap.xml,這樣比網(wǎng)上很多方法是在保存、發(fā)布文章時生成xml好一些,不會造成處理文章卡的現(xiàn)象。在WordPress主題文件functions.php中或者使用Code Snippets插件添加自定義代碼:

// 判斷定時計劃是否存在
if ( ! wp_next_scheduled( 'sitemap_xml' ) ) {
  wp_schedule_event( time(), 'twicedaily', 'sitemap_xml' ); // 每天兩次
}
add_action( 'sitemap_xml', 'sitemap_xml_func' );
 
// 定時計劃執(zhí)行函數(shù)
function sitemap_xml_func() {
  // 獲取文章數(shù)量
  $count_posts = wp_count_posts();
  if ( $count_posts ) {
    $published_posts = $count_posts->publish;
    $sitemap_num = $published_posts / 3000; // 每個xml文件最多包含3000篇文章
    $sitemap_num = ceil($sitemap_num);
 
    // 創(chuàng)建xml文件
    for ($i = 1; $i <= $sitemap_num; $i++) {
      $postsForSitemap = get_posts(array(
        'numberposts' => 3000,
        'orderby' => 'modified',
        'post_type'  => array('post'),
        'order'    => 'DESC',
        'offset' => 3000 * ($i - 1)
      ));
      $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
      $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
      foreach($postsForSitemap as $post) {
        setup_postdata($post);
        $post_url = get_permalink($post->ID);
        $post_date = get_the_modified_date( 'c',$post->ID );
 
        $sitemap .= '<url>'.
              '<loc>'. $post_url .'</loc>'.
            '<lastmod>'.  $post_date .'</lastmod>'.
              // '<lastmod>'. $postdate[0] .'</lastmod>'.
          // '<changefreq>monthly</changefreq>'.
          '</url>';
      }
      $sitemap .= '</urlset>';
      $fp = fopen(ABSPATH . "sitemap-".$i.".xml", 'w');
      fwrite($fp, $sitemap);
      fclose($fp);
    }
 
    // 創(chuàng)建sitemap.xml文件
    $sitemap_all = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap_all .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    for ($i = 1; $i <= $sitemap_num; $i++) {
      $sitemap_all .= '<sitemap>'.
            '<loc>'. get_bloginfo('url') .'/sitemap-'.$i.'.xml</loc>'.
            '<lastmod>'. date('c') .'</lastmod>'.
          '</sitemap>';
    }
    $sitemap_all .= '</sitemapindex>';
    $fp = fopen(ABSPATH . "sitemap.xml", 'w');
    fwrite($fp, $sitemap_all);
    fclose($fp);
  }
}

未經(jīng)允許不得轉載:445IT之家 » WordPress定時生成Sitemap XML地圖(非插件)

贊 (0) 打賞

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

微信掃一掃打賞