下面由WordPress教程欄目給大家介紹WordPress增加網站地圖的方法,希望對需要的朋友有所幫助!
先說一句口號:能用代碼解決的,堅決不用插件!
wordpress的網站地圖用一般的生成工具,生成之后都不能用,比如織夢我常用sitemapx,結果放在wordpress就出錯了。
WordPress生成網站地圖的插件也有很多,大家可以自行百度,這里主要是講利用代碼生成。
1.先將以下代碼將保存為 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>' ?> <!-- generated-on=<?php echo get_lastpostdate('blog'); ?> Diy By 獨立站大學(http://dulizhandaxue.com)--> ??<url> ??????<loc><?php echo get_home_url(); ?></loc> ??????<lastmod><?php $ltime = get_lastpostmodified(GMT);$ltime = gmdate('Y-m-dTH: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>
?2.編輯 nginx 偽靜態規則,新增如下規則:
rewrite?^/sitemap.xml$?/sitemap.php?last;
3.編輯網站根目錄的.htaccess(如果沒有則新建為txt文檔),加入如下規則:
RewriteRule?^(sitemap).xml$?$1.php
直接訪問網站域名+sitemap.xml即可。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END