欢迎光临
我们一直在努力

免插件实现两种格式的网站地图功能

前言

网站地图一般所有网站都有的,之前一直都是用百度地图插件,自动生成网站地图,包括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;

效果预览

网站地图XML 网站地图HTML

相关链接

下载代码文件

窗外天空
关注公众号『窗外天空』

获取更多建站运营运维新知!
互联网创业、前沿技术......

赞(0) 打赏
文章名称:《免插件实现两种格式的网站地图功能》
文章链接:https://www.nixonli.com/18349.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

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

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏