无插件,纯代码实现网站地图功能,希望云落推荐的这个你能喜欢
前言
网站地图一般所有网站都有的,之前一直都是用百度地图插件,自动生成网站地图,包括xml格式和html格式,但是如果插件能少一个而其功能还不少,那也是极好的。折翅云落把来自奶嘴的旧的教程拿来重新写下,给出一个稍微修改的网站地图方案
生成HTML地图
下载文章底部的文件,放到主题的页面模板那里,一般和你的友情链接模板在一起,然后在WordPress后台新建页面,选择网站地图模板,具体可以先看看上面的原版教程。
下面开始不太一样了
新建页面时候,别名命名为sitemap
,然后正常来说链接就是http://网站域名/sitemap
但是这个和正常的HTML地图链接不太一样,我们想要的是http://网站域名/sitemap.html 是把,其实就是页面伪静态的问题吧
在主题functions.php文件添加以下代码
//页面伪静态 add_action('init', 'html_page_permalink', -1); register_activation_hook(__FILE__, 'active'); register_deactivation_hook(__FILE__, 'deactive'); function html_page_permalink() { global $wp_rewrite; if ( !strpos($wp_rewrite->get_page_permastruct(), '.html')){ $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html'; } } add_filter('user_trailingslashit', 'no_page_slash',66,2); function no_page_slash($string, $type){ global $wp_rewrite; if ($wp_rewrite->using_permalinks() && $wp_rewrite->use_trailing_slashes==true && $type == 'page'){ return untrailingslashit($string); }else{ return $string; } } function active() { global $wp_rewrite; if ( !strpos($wp_rewrite->get_page_permastruct(), '.html')){ $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html'; } $wp_rewrite->flush_rules(); } function deactive() { global $wp_rewrite; $wp_rewrite->page_structure = str_replace(".html","",$wp_rewrite->page_structure); $wp_rewrite->flush_rules(); }
然后需要在设置——固定连接那里重新保存一下,不然会404的
XML网站地图
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'; ?> <!-- generated-on=<?php echo get_lastpostdate('blog'); ?>--> <url> <loc><?php echo site_url(); ?></loc> <lastmod><?php echo get_lastpostdate('blog'); ?></lastmod> <changefreq>daily</changefreq> <priority>1.0</priority> </url> <?php header("Content-type: text/xml"); $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 } // end foreach ?> </urlset>
XML地图比较简单,上面这段代码保存为sitemap.php
,保存在WordPress网站根目录,一般和wp-config.php
在同一个目录。
然后需要添加转发规则
RewriteEngine On RewriteBase / RewriteRule ^sitemap.xml$ sitemap.php
将这句代码添加到.htaccess文件,云落就是这样滴!
nginx下的规则是这样滴:
rewrite ^/sitemap.xml$ /sitemap.php;
效果预览
[bb href='https://gitcafe.net/sitemap.php']网站地图XML[/bb] [yb href='https://gitcafe.net/sitemap.html']网站地图HTML[/yb]
相关链接
[gb href='http://pan.baidu.com/s/1gdj2QT9']下载代码文件[/gb]
版权声明
-- 完 --
这个不错,收藏了
nginx环境下上,代码加到function文件,然后网站就500错误,怎么回事呢?
签到成功!签到时间:2016-12-27 11:06:48,每日打卡,生活更精彩哦~
这个挺不错的
主题改的不错