很多人都在寻找WordPress中好用的SiteMap生成工具,但是网络鱼龙混杂,很难找到真正好用的插件,于是博主就来教大家如何自己制作一款属于自己的SiteMap生成插件。
本站案例
本站SiteMap的XML格式:https://www.svlik.com/sitemap.xml
本站SiteMap的HTML格式:https://www.svlik.com/sitemap.html
本站MIPSiteMap的XML格式:https://www.svlik.com/mip_sitemap.xml
准备工作
首先创建一个文件夹名为Svlik-SiteMap,然后在文件夹内创建3个文件,名字分别为sitemap.html、Svlik-SiteMap.php、Svlik-SiteMap-Function.php即可。
写入代码
将以下代码填入对应的文件中即可。
sitemap.html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>%blog_title% - %blog_name%</title>
<meta name="keywords" content="%blog_keywords%" />
<meta name="author" content="%Fanly_author%" />
<meta name="copyright" content="%Fanly_copyright%" />
<style type="text/css">
body {font-family:Verdana;font-size: 12px;margin:0;color:#000;background:#fff;}
a{color:#333;text-decoration:none;}
h1{text-align:center;margin-top:20px}
li{margin-top:8px;}
#nav, #content{padding: 8px; border: 1px solid #EEEEEE; clear: both; width: 95%; margin: auto; margin-top: 10px;}
#footer{text-align:center;}
</style>
</head>
<body>
<h1>%blog_name% SiteMap</h1>
<div id="nav"><a href="%blog_home%"><strong>%blog_name%</strong></a> » <a href="%sitemap_url%">%blog_title%</a></div>
<div id="content">
<h2>%RecentPost%</h2>
<ul>%contents%</ul>
%Fanly_contents%
</div>
<div id="nav">%footnote%: <a href="%blog_home%">%blog_name%</a></div>
<div id="footer">
<p><b><a href="%blog_home%/sitemap.xml" target="_blank">XML SiteMap</a></b> Latest Update: %updated_time%</p>
<p>© <a href="%blog_home%" target="_blank" title="%blog_name%">%blog_name%</a></p>
</div>
</body>
</html>
Svlik-SiteMap.php代码
<?php
/*
Plugin Name: Svlik SiteMap
Plugin URI: https://www.svlik.com/
Description: WordPress XML地图插件,MIP版。
Author: Svlik
Version: 1.1
Author URI: https://www.svlik.com/
*/
//define the field name of database
define('SITEMAP_OPTION','Svlik_SiteMap');
//load
require_once("Svlik-SiteMap-Function.php");
//add a Menu,like "Sitemap"
add_action('admin_menu','Svlik_SiteMap');
function Svlik_SiteMap() {
//Add a page to the options section of the website
if (current_user_can('manage_options'))
add_submenu_page('options-general.php','Svlik SiteMap', 'Svlik SiteMap', 'manage_options', 'Svlik_SiteMap', 'fanly_sitemap_menu', '');
}
//add plugin link
add_filter( 'plugin_action_links', 'Svlik_SiteMap_Add_Link', 10, 5 );
function Svlik_SiteMap_Add_Link( $actions, $plugin_file ) {
static $plugin;
if (!isset($plugin))
$plugin = plugin_basename(__FILE__);
if ($plugin == $plugin_file) {
$settings = array('settings' => '<a href="'.('options-general.php?page=Svlik_SiteMap').'">' . __('Settings') . '</a>');
$site_link = array('support' => '<a href="http://zhangzifan.com" target="_blank">Svlik</a>');
$actions = array_merge($settings, $actions);
$actions = array_merge($site_link, $actions);
}
return $actions;
}
//remove plugin
add_filter( 'plugin_action_links', 'Svlik_SiteMap_remove_plugin_link', 10, 4 );
function Svlik_SiteMap_remove_plugin_link( $actions, $plugin_file, $plugin_data, $context ){
if(isset($actions['edit'])){
switch($plugin_file){
case 'Svlik-SiteMap/Svlik-SiteMap.php':unset( $actions['edit'] );
break;
}
}
return $actions;
}
//custom message
function sitemap_topbarmessage($msg) {
echo '<div class="updated fade" id="message"><p>' . $msg . '</p></div>';
}
//get options
function get_fanly_sitemap(){
$fanly_sitemap = array();
$get_fanly_sitemap = get_option(SITEMAP_OPTION);
if( $get_fanly_sitemap ){
list( $fanly_sitemap['MIP_XML_Sitemap'],$fanly_sitemap['MIP_Site'],$fanly_sitemap['XML_Sitemap'], $fanly_sitemap['Html_Sitemap'], $fanly_sitemap['sitemap_when_post'], $fanly_sitemap['post_limit_1000'], $fanly_sitemap['post'], $fanly_sitemap['page'], $fanly_sitemap['cat'], $fanly_sitemap['tag'] ) = explode("|",$get_fanly_sitemap);
}else{
if( !$fanly_sitemap['XML_Sitemap'] ){ $fanly_sitemap['XML_Sitemap'] = 1; }
if( !$fanly_sitemap['sitemap_when_post'] ){ $fanly_sitemap['sitemap_when_post'] = 1; }
if( !$fanly_sitemap['post_limit_1000'] ){ $fanly_sitemap['post_limit_1000'] = 1; }
}
return $fanly_sitemap;
}
//sitemap page
function fanly_sitemap_form() {
$fanly_sitemap = get_fanly_sitemap();
?>
<div class="wrap">
<div class="postbox-container" style="width:75%;">
<div class="metabox-holder">
<div class="meta-box-sortables">
<div class="tool-box">
<a name="sitemap_options"></a><form name="sitemap_options" method="post" action="">
<input type="hidden" name="action" value="build_options" />
<table>
<tr><td><h3>基本配置</h3></td></tr>
<tr><td>生成MIP XML</td><td>
<?php
if(class_exists('SvlikDomainTheme')) {
$SvlikDomainTheme = unserialize(get_option("SvlikDomainTheme_options"));
echo '<select name="MIP_XML_Sitemap" id="Site">';
foreach($SvlikDomainTheme as $domain){
if($fanly_sitemap['MIP_XML_Sitemap'] == $domain['url']){$sl = ' selected';}else{$sl='';}
echo '<option value="'.$domain['url'].'"'.$sl.'>'.$domain['url'].'</option>';
}
if($fanly_sitemap['MIP_XML_Sitemap'] == $fanly_sitemap['MIP_Site']){$custom = ' selected';}else{$custom='';}
echo '<option value="custom"'.$custom.'>自定义MIP Site</option>';
if($fanly_sitemap['MIP_XML_Sitemap'] == '0'){$sl = ' selected';}else{$sl='';}
echo '<option value="0"'.$sl.'>不生成</option>';
echo '</select>';
}else{
echo '<select name="MIP_XML_Sitemap" id="Site">';
if($fanly_sitemap['MIP_XML_Sitemap'] == '0'){$sl = ' selected';}else{$sl='';}
echo '<option value="0"'.$sl.'>不生成</option>';
if($fanly_sitemap['MIP_XML_Sitemap'] == $fanly_sitemap['MIP_Site']){$custom = ' selected';}else{$custom='';}
echo '<option value="custom"'.$custom.'>自定义MIP Site</option>';
echo '<option value="0">更多域名需要SvlikDomainTheme插件支持</option>';
echo '</select>';
}
?>
</td></tr>
<tr id="CustomSite"><td>自定义 MIP Site</td><td><input type="text" name="MIP_Site" value="<?php echo $fanly_sitemap['MIP_Site']?>" /></td></tr>
<tr><td>生成 XML 地图</td><td><input type="checkbox" name="XML_Sitemap" value="1" <?php if( $fanly_sitemap['XML_Sitemap'] ) { echo 'checked="checked"'; } ?> /></td></tr>
<tr><td>生成 Html 地图</td><td><input type="checkbox" name="Html_Sitemap" value="1" <?php if( $fanly_sitemap['Html_Sitemap'] ) { echo 'checked="checked"'; } ?> /></td><td><a title="静态HTML网站地图">[?]</a><td></tr>
<tr><td>发布文章自动更新</td><td><input type="checkbox" name="sitemap_when_post" value="1" <?php if( $fanly_sitemap['sitemap_when_post'] ) { echo 'checked="checked"'; } ?> /></td></tr>
<tr><td>只生成最近的文章(1000以内)</td><td><input type="checkbox" name="post_limit_1000" value="1" <?php if( $fanly_sitemap['post_limit_1000'] ) { echo 'checked="checked"'; } ?> /></td><td><a title="只需将最近一个更新周期内新增的和变化了的文章包含在XML页面上,过多的数量只会增加服务器的负担。">[?]</a><td></tr>
<tr><td>包含链接</td><td>
<label style="padding-right:10px;"><input type="checkbox" name="post" value="1" checked readonly />文章</label>
<label style="padding-right:10px;"><input type="checkbox" name="page" value="1" <?php if( $fanly_sitemap['page'] ) { echo 'checked="checked"'; } ?> />页面</label>
<label style="padding-right:10px;"><input type="checkbox" name="cat" value="1" <?php if( $fanly_sitemap['cat'] ) { echo 'checked="checked"'; } ?> />分类</label>
<label style="padding-right:10px;"><input type="checkbox" name="tag" value="1" <?php if( $fanly_sitemap['tag'] ) { echo 'checked="checked"'; } ?> />标签</label>
</td></tr>
</table>
<p class="submit"><input type="submit" class="button-primary" /></p>
</form>
<script type="text/javascript">
jQuery(function(){
<?php if($fanly_sitemap['MIP_XML_Sitemap'] != $fanly_sitemap['MIP_Site']){?>
jQuery("#CustomSite").hide();
<?php }?>
jQuery("select#Site").change(function(){
var selected = jQuery("select#Site").val();
if(selected == "custom"){
jQuery("#CustomSite").show();
}else{
jQuery("#CustomSite").hide();
}
});
});
</script>
</div>
<div class="tool-box">
<h3 class="title">生成XML文件</h3>
<form name="sitemap_build" method="post" action="">
<input type="hidden" name="action" value="build_xml" />
<p class="submit"><input type="submit" class="button-primary" value="更新地图" /></p>
</form>
</div>
<?php
//show the XML file if exist
fanly_xml_file_exist();
?>
</div>
</div>
</div>
</div>
<?php
}
//sitemap page
function fanly_sitemap_menu(){
//Perform any action
if(isset($_POST["action"])) {
if ($_POST["action"]=='build_options') {update_fanly_sitemap(); }
if ($_POST["action"]=='build_xml') { fanly_sitemap_build();}
}
//Definition
echo '<h2>Svlik SiteMap</h2>';
//Introduction
echo '<p>一个支持WordPress生成XML地图、HTML地图以及支持生成MIP XML地图文件。</p>';
//show the option Form
fanly_sitemap_form();
//Show the plugins Author
Svlik_sidebar();
}
//update the options
function update_fanly_sitemap() {
if ($_POST['action']=='build_options'){
$MIP_XML_Sitemap = $_POST['MIP_XML_Sitemap'];
if($MIP_XML_Sitemap == 'custom'){
$MIPSite = $_POST['MIP_Site'];
if(strstr($MIPSite,"//")){
$MIPSite = strtok(str_replace("//","",strstr($MIPSite,"//")), '/');
}else{$MIPSite = strtok($MIPSite, '/');}
$MIP_XML_Sitemap = $MIPSite;
$MIP_Site = $MIPSite;
}else{$MIP_XML_Sitemap = $_POST['MIP_XML_Sitemap'];}
if(!$MIP_XML_Sitemap){ $MIP_XML_Sitemap = 0; }
if(!$MIP_Site){ $MIP_Site = ''; }
$XML_Sitemap = $_POST['XML_Sitemap'];
if(!$XML_Sitemap){ $XML_Sitemap = 0; }
$Html_Sitemap = $_POST['Html_Sitemap'];
if(!$Html_Sitemap){ $Html_Sitemap = 0; }
$sitemap_when_post = $_POST['sitemap_when_post'];
if(!$sitemap_when_post){ $sitemap_when_post = 0; }
$post_limit_1000 = $_POST['post_limit_1000'];
if(!$post_limit_1000){ $post_limit_1000 = 0; }
$fanly_post = $_POST['post'];
if(!$fanly_post){ $fanly_post = 0; }
$fanly_page = $_POST['page'];
if(!$fanly_page){ $fanly_post = 0; }
$fanly_cat = $_POST['cat'];
if(!$fanly_cat){ $fanly_cat = 0; }
$fanly_tag = $_POST['tag'];
if(!$fanly_tag){ $fanly_tag = 0; }
$sitemap_options = implode('|',array($MIP_XML_Sitemap,$MIP_Site,$XML_Sitemap, $Html_Sitemap, $sitemap_when_post, $post_limit_1000, $fanly_post, $fanly_page, $fanly_cat, $fanly_tag));
update_option(SITEMAP_OPTION,$sitemap_options);
sitemap_topbarmessage('更新配置成功');
fanly_sitemap_build();
}
}
//build the XML file, sitemap.xml
add_action('do_sitemap_by_post','fanly_sitemap_build',2,0);
function fanly_sitemap_build() {
global $wpdb, $post;
$fanly_sitemap = get_fanly_sitemap();
if($fanly_sitemap['post_limit_1000']){ $Svlik_limit = '1000'; } else { $Svlik_limit = '10000'; }
## $Svlik_contents , $Svlik_limit = '1000'
$sql_mini = "select ID,post_modified_gmt,post_date_gmt,post_type FROM $wpdb->posts
WHERE post_password = ''
AND (post_type != 'revision' AND post_type != 'attachment' AND post_type != 'nav_menu_item')
AND post_status = 'publish'
ORDER BY post_modified_gmt DESC
LIMIT 0,$Svlik_limit
";
$recentpost = $wpdb->get_results($sql_mini);
if($recentpost){
foreach ($recentpost as $post){
if( $post->post_type == 'page' ){
if(!$fanly_sitemap['page']){ continue; } //跳过
$loc = get_page_link($post->ID);
$loc = Svlik_EscapeXML($loc);
if(!$loc){ continue; }
if($post->post_modified_gmt == '0000-00-00 00:00:00'){ $post_date_gmt = $post->post_date_gmt; } else { $post_date_gmt = $post->post_modified_gmt; }
$lastmod = date("Y-m-d\TH:i:s+00:00",Svlik_GetTimestampFromMySql($post_date_gmt));
$changefreq = 'weekly';
$priority = '0.3';
$xml_content_page .= "<url>";
$xml_content_page .= "<loc>$loc</loc>";
$xml_content_page .= "<lastmod>$lastmod</lastmod>";
$xml_content_page .= "<changefreq>$changefreq</changefreq>";
$xml_content_page .= "<priority>$priority</priority>";
$xml_content_page .= "</url>";
}
}
$args = array(
'showposts' => $Svlik_limit,//显示文章数量
'ignore_sticky_posts' => 1, //忽略sticky_posts,即不置顶(不将置顶文章提至最前),但是输出置顶文章
);
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post();
$loc = get_permalink();
$loc = Svlik_EscapeXML($loc);
if(!$loc){ continue; }
$lastmod = get_the_modified_time('Y-m-d\TH:i:s+00:00');
$changefreq = 'monthly';
$priority = '0.6';
$xml_content_post .= "<url>";
$xml_content_post .= "<loc>$loc</loc>";
$xml_content_post .= "<lastmod>$lastmod</lastmod>";
$xml_content_post .= "<changefreq>$changefreq</changefreq>";
$xml_content_post .= "<priority>$priority</priority>";
$xml_content_post .= "</url>";
endwhile;
## get_category_link
$category_ids = get_all_category_ids();
foreach($category_ids as $cat_id) {
if(!$fanly_sitemap['cat']){ continue; } //跳过
$loc = get_category_link($cat_id);
$loc = Svlik_EscapeXML($loc);
if(!$loc){ continue; }
$lastmod = date("Y-m-d\TH:i:s+00:00",current_time('timestamp', '1'));
$changefreq = 'Weekly';
$priority = '0.3';
$xml_content_cat .= "<url>";
$xml_content_cat .= "<loc>$loc</loc>";
$xml_content_cat .= "<lastmod>$lastmod</lastmod>";
$xml_content_cat .= "<changefreq>$changefreq</changefreq>";
$xml_content_cat .= "<priority>$priority</priority>";
$xml_content_cat .= "</url>";
}
## get_tags
$all_the_tags = get_tags();
if($all_the_tags){
foreach($all_the_tags as $this_tag) {
if(!$fanly_sitemap['tag']){ continue; } //跳过
$tag_id = $this_tag->term_id;
$loc = get_tag_link($tag_id);
$loc = Svlik_EscapeXML($loc);
if(!$loc){ continue; }
$lastmod = date("Y-m-d\TH:i:s+00:00",current_time('timestamp', '1'));
$changefreq = 'Weekly';
$priority = '0.3';
$xml_content_tag .= "<url>";
$xml_content_tag .= "<loc>$loc</loc>";
$xml_content_tag .= "<lastmod>$lastmod</lastmod>";
$xml_content_tag .= "<changefreq>$changefreq</changefreq>";
$xml_content_tag .= "<priority>$priority</priority>";
$xml_content_tag .= "</url>";
}
}
##
$xml_contents = $xml_content_post.$xml_content_page.$xml_content_cat.$xml_content_tag;
}
## XML
if($fanly_sitemap['XML_Sitemap']){
fanly_sitemap_build_xml($xml_contents);
}else{//删除
Svlik_SiteMap_DEL('sitemap.xml');
}
## MIP XML
if($fanly_sitemap['MIP_XML_Sitemap']){
build_mip_sitemap_xml($xml_contents);
}else{//删除
Svlik_SiteMap_DEL('mip_sitemap.xml');
}
## Html
if($fanly_sitemap['Html_Sitemap']){
fanly_sitemap_build_html();
}else{//删除
Svlik_SiteMap_DEL('sitemap.html');
}
if(function_exists('wp_clear_scheduled_hook')) { wp_clear_scheduled_hook('do_sitemap_by_post'); }
//sitemap_is_auto_daily();
}
function Svlik_SiteMap_DEL($file){
$file = Svlik_GetHomePath().$file;//基于站点根目录
if(is_file($file)){
if(unlink($file)){
sitemap_topbarmessage("文件{$file}删除完毕!");
}else{
//echo "文件{$file}删除失败...!尝试修改文件权限删除...";
if(chmod($file,0777)){
unlink($file);
sitemap_topbarmessage("文件{$file}权限修改后删除完毕...");
}else{
sitemap_topbarmessage("文件{$file}无法自动删除,请手动通过FTP删除!");
}
}
}
}
//MIP XML
function build_mip_sitemap_xml($xml_contents){
$Svlik_blog_url = home_url();
$blogtime = current_time('timestamp', '1');
$Svlik_blog_time = date("Y-m-d\TH:i:s+00:00",$blogtime);
$xml_begin = '<?xml version="1.0" encoding="UTF-8"?>'.fanly_xml_annotate().'<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">';
$xml_home = "<url><loc>$Svlik_blog_url</loc><lastmod>$Svlik_blog_time</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>";
$xml_end = '</urlset>';
if($xml_contents){
$fanly_sitemap = get_fanly_sitemap();
$xml = $xml_begin.$xml_home.$xml_contents.$xml_end;
$xml = str_replace(str_replace("//","",strstr(home_url(),"//")),$fanly_sitemap['MIP_XML_Sitemap'],$xml);
//save XML file as sitemap.xml
$Svlik_GetHomePath = Svlik_GetHomePath();
$filename = $Svlik_GetHomePath.'mip_sitemap.xml';
if( IsFileWritable($Svlik_GetHomePath) || IsFileWritable($filename) ){
file_put_contents("$filename","$xml");
@chmod($filename, 0777);
//Messages
sitemap_topbarmessage('更新 MIP XML 文件成功!');
}else{
//Messages
sitemap_topbarmessage('文件或目录不可写,请修改根目录权限改为777。');
}
}
}
//XML
function fanly_sitemap_build_xml($xml_contents){
$Svlik_blog_url = home_url();
$blogtime = current_time('timestamp', '1');
$Svlik_blog_time = date("Y-m-d\TH:i:s+00:00",$blogtime);
$xml_begin = '<?xml version="1.0" encoding="UTF-8"?>'.fanly_xml_annotate().'<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">';
$xml_home = "<url><loc>$Svlik_blog_url</loc><lastmod>$Svlik_blog_time</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>";
$xml_end = '</urlset>';
if($xml_contents){
$xml = $xml_begin.$xml_home.$xml_contents.$xml_end;
//save XML file as sitemap.xml
$Svlik_GetHomePath = Svlik_GetHomePath();
$filename = $Svlik_GetHomePath.'sitemap.xml';
if( IsFileWritable($Svlik_GetHomePath) || IsFileWritable($filename) ){
file_put_contents("$filename","$xml");
@chmod($filename, 0777);
//Messages
sitemap_topbarmessage('更新 XML 文件成功!');
}else{
//Messages
sitemap_topbarmessage('文件或目录不可写,请修改根目录权限改为777。');
}
}
}
function fanly_sitemap_build_html(){
global $wpdb;
$fanly_sitemap = get_fanly_sitemap();
if($fanly_sitemap['post_limit_1000']){ $Svlik_limit = '1000'; } else { $Svlik_limit = '10000'; }
##文章
$html_contents = $html_category_contents = $html_page_contents = $html_tag_contents = '';
$args = array(
'showposts' => $Svlik_limit,//显示文章数量
'ignore_sticky_posts' => 1, //忽略sticky_posts,即不置顶(不将置顶文章提至最前),但是输出置顶文章
);
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post();
$html_contents .= '<li><a href="'.get_permalink().'" title="'.get_the_title().'" target="_blank">'.get_the_title().'</a></li>';
endwhile;
if($fanly_sitemap['cat'])
$html_category_contents = '<h2>分类</h2><ul>'.wp_list_categories('echo=0&title_li=').'</ul>';
if($fanly_sitemap['page'])
$html_page_contents = '<h2>页面</h2><ul>'.wp_list_pages('echo=0&title_li=').'</ul>';
if($fanly_sitemap['tag'])
$html_tag_contents = '<h2>标签</h2>'.wp_tag_cloud('echo=0&number=245');
$Svlik_contents = $html_page_contents.$html_category_contents.$html_tag_contents;
$blog_title = 'SiteMap';
$blog_name = get_bloginfo('name');
$blog_keywords = 'SiteMap,网站地图'.$blog_name;
$Svlik_author = $blog_name;
$Svlik_copyright = 'www.Svlik.com';
$blog_home = get_bloginfo('url');
$sitemap_url = get_bloginfo('url').'/sitemap.html';
$recentpost = '最新文章';
$footnote = '首页';
$updated_time = current_time('mysql');
if($html_contents) {
$path_html = GetPluginPath().'sitemap.html';
$html = file_get_contents("$path_html");
$html = str_replace("%blog_title%",$blog_title,$html);
$html = str_replace("%blog_name%",$blog_name,$html);
$html = str_replace("%blog_home%",$blog_home,$html);
$html = str_replace("%blog_keywords%",$blog_keywords,$html);
$html = str_replace("%Svlik_author%",$Svlik_author,$html);
$html = str_replace("%Svlik_copyright%",$Svlik_copyright,$html);
$html = str_replace("%sitemap_url%",$sitemap_url,$html);
$html = str_replace("%footnote%",$footnote,$html);
$html = str_replace("%RecentPost%",$recentpost,$html);
$html = str_replace("%updated_time%",$updated_time,$html);
$html = str_replace("%contents%",$html_contents,$html);
$html = str_replace("%Svlik_contents%",$Svlik_contents,$html);
$Svlik_GetHomePath = Svlik_GetHomePath();
$filename_html = $Svlik_GetHomePath.'sitemap.html';
if( IsFileWritable($Svlik_GetHomePath) || IsFileWritable($filename_html) ){
file_put_contents("$filename_html","$html");
@chmod($filename_html, 0777);
//Messages
sitemap_topbarmessage('更新HTML地图成功!');
}
}
}
## Auto
add_action('init','sitemap_is_auto_daily',1001,0);
function sitemap_is_auto_daily() {
$Svlik_updatePeri = $Svlik_updatePeri*60*60*24;
wp_schedule_single_event(time()+$Svlik_updatePeri, 'do_this_auto_daily');
add_action('do_this_auto_daily','fanly_sitemap_build',2,0);
}
add_action('publish_post', 'sitemap_by_post');
function sitemap_by_post($post_ID) {
$get_fanly_sitemap = get_fanly_sitemap();
if($get_fanly_sitemap['sitemap_when_post'] == '1'){
wp_clear_scheduled_hook('do_sitemap_by_post');
wp_schedule_single_event(time()+30, 'do_sitemap_by_post');
}
return $post_ID;
}
?>
Svlik-SiteMap-Function.php代码
<?php
/*
*@author arnee
*google-sitemap-TearSnow
*/
#region PHP5 compat functions
if (!function_exists('file_get_contents')) {
/**
* Replace file_get_contents()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.file_get_contents
* @author Aidan Lister <aidan - php - net>
* @version $Revision: 1.21 $
* @internal resource_context is not supported
* @since PHP 5
*/
function file_get_contents($filename, $incpath = false, $resource_context = null) {
if (false === $fh = fopen($filename, 'rb', $incpath)) {
user_error('file_get_contents() failed to open stream: No such file or directory', E_USER_WARNING);
return false;
}
clearstatcache();
if ($fsize = @filesize($filename)) {
$data = fread($fh, $fsize);
} else {
$data = '';
while (!feof($fh)) {
$data .= fread($fh, 8192);
}
}
fclose($fh);
return $data;
}
}
if(!function_exists('file_put_contents')) {
if (!defined('FILE_USE_INCLUDE_PATH')) {
define('FILE_USE_INCLUDE_PATH', 1);
}
if (!defined('LOCK_EX')) {
define('LOCK_EX', 2);
}
if (!defined('FILE_APPEND')) {
define('FILE_APPEND', 8);
}
/**
* Replace file_put_contents()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.file_put_contents
* @author Aidan Lister <aidan - php - net>
* @version $Revision: 1.25 $
* @internal resource_context is not supported
* @since PHP 5
* @require PHP 4.0.0 (user_error)
*/
function file_put_contents($filename, $content, $flags = null, $resource_context = null) {
// If $content is an array, convert it to a string
if (is_array($content)) {
$content = implode('', $content);
}
// If we don't have a string, throw an error
if (!is_scalar($content)) {
user_error('file_put_contents() The 2nd parameter should be either a string or an array',E_USER_WARNING);
return false;
}
// Get the length of data to write
$length = strlen($content);
// Check what mode we are using
$mode = ($flags & FILE_APPEND)?'a':'wb';
// Check if we're using the include path
$use_inc_path = ($flags & FILE_USE_INCLUDE_PATH)?true:false;
// Open the file for writing
if (($fh = @fopen($filename, $mode, $use_inc_path)) === false) {
user_error('file_put_contents() failed to open stream: Permission denied',E_USER_WARNING);
return false;
}
// Attempt to get an exclusive lock
$use_lock = ($flags & LOCK_EX) ? true : false ;
if ($use_lock === true) {
if (!flock($fh, LOCK_EX)) {
return false;
}
}
// Write to the file
$bytes = 0;
if (($bytes = @fwrite($fh, $content)) === false) {
$errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s',$length,$filename);
user_error($errormsg, E_USER_WARNING);
return false;
}
// Close the handle
@fclose($fh);
// Check all the data was written
if ($bytes != $length) {
$errormsg = sprintf('file_put_contents() Only %d of %d bytes written, possibly out of free disk space.',$bytes,$length);
user_error($errormsg, E_USER_WARNING);
return false;
}
// Return length
return $bytes;
}
}
#endregion
/*
*@author arnee
*google-sitemap-TearSnow
*/
if (!function_exists('Svlik_GetHomePath')) {
function Svlik_GetHomePath() {
$res="";
//Check if we are in the admin area -> get_home_path() is avaiable
if(function_exists("get_home_path")) {
$res = get_home_path();
} else {
//get_home_path() is not available, but we can't include the admin
//libraries because many plugins check for the "check_admin_referer"
//function to detect if you are on an admin page. So we have to copy
//the get_home_path function in our own...
$home = get_option( 'home' );
if ( $home != '' && $home != get_option( 'siteurl' ) ) {
$home_path = parse_url( $home );
$home_path = $home_path['path'];
$root = str_replace( $_SERVER["PHP_SELF"], '', $_SERVER["SCRIPT_FILENAME"] );
$home_path = trailingslashit( $root.$home_path );
} else {
$home_path = ABSPATH;
}
$res = $home_path;
}
return $res;
}
}
/*
*@author arnee
*/
function Svlik_EscapeXML($string) {
return str_replace ( array ( '&', '"', "'", '<', '>'), array ( '&' , '"', ''' , '<' , '>'), $string);
}
/**
* Checks if a file is writable and tries to make it if not.
*
* @since 3.05b
* @access private
* @author VJTD3 <http://www.VJTD3.com>
* @return bool true if writable
*/
if (!function_exists('IsFileWritable')) {
function IsFileWritable($filename) {
clearstatcache();
//can we write?
if(!is_writable($filename)) {
//no we can't.
if(!@chmod($filename, 0666)) {
$pathtofilename = dirname($filename);
//Lets check if parent directory is writable.
if(!is_writable($pathtofilename)) {
//it's not writeable too.
if(!@chmod($pathtoffilename, 0666)) {
//darn couldn't fix up parrent directory this hosting is foobar.
//Lets error because of the permissions problems.
return false;
}
}
}
}
//we can write, return 1/true/happy dance.
return true;
}
}
/*
*
*Un-quotes quoted string\
*/
if (!function_exists('stripslashes_deep')) {
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
}
/**
* Returns the path to the directory where the plugin file is located
* @since 3.0b5
* @access private
* @author Arne Brachhold
* @return string The path to the plugin directory
*/
if (!function_exists('GetPluginPath')) {
function GetPluginPath() {
$path = dirname(__FILE__);
return trailingslashit(str_replace("\\","/",$path));
}
}
/**
* Returns the URL to the directory where the plugin file is located
* @since 3.0b5
* @access private
* @author Arne Brachhold
* @return string The URL to the plugin directory
*/
if (!function_exists('GetPluginUrl')) {
function GetPluginUrl() {
//Try to use WP API if possible, introduced in WP 2.6
if (function_exists('plugins_url')) return trailingslashit(plugins_url(basename(dirname(__FILE__))));
//Try to find manually... can't work if wp-content was renamed or is redirected
$path = dirname(__FILE__);
$path = str_replace("\\","/",$path);
$path = trailingslashit(get_bloginfo('wpurl')) . trailingslashit(substr($path,strpos($path,"wp-content/")));
return $path;
}
}
/**
*load_plugin_textdomain('sitemap');
*@author Arne Brachhold
*/
function Svlik_sidebar() {?>
<style type="text/css">
a.Svlik_button {
padding:4px;
display:block;
padding-left:25px;
background-repeat:no-repeat;
background-position:5px 50%;
text-decoration:none;
border:none;
}
</style>
<?php
}
function fanly_xml_file_exist() {
$Svlik_blog_url = home_url();
$filePath = Svlik_GetHomePath();
$filename = $filePath.'sitemap.xml';
$filemipname = $filePath.'mip_sitemap.xml';
echo '<div class="tool-box">';
echo '<h3 class="title">XML 文件状态</h3>';
if(file_exists($filemipname)){
$fanly_sitemap = get_fanly_sitemap();
$mipurl =str_replace(strtok(str_replace("//","",strstr($Svlik_blog_url,"//")), '/'),$fanly_sitemap['MIP_XML_Sitemap'],$Svlik_blog_url);
date_default_timezone_set ('Asia/Shanghai');
$filemtime=date("Y-m-d H:i:s",filemtime("$filemipname"));
echo '<p>检查 MIP XML 文件:<a href="'.$mipurl.'/mip_sitemap.xml'.'" target="_blank">'.$mipurl.'/mip_sitemap.xml'.'</a>('.$filemtime.')</p>';
}
if(file_exists($filename)){
date_default_timezone_set ('Asia/Shanghai');
$filemtime=date("Y-m-d H:i:s",filemtime("$filename"));
echo '<p>检查 XML 文件:<a href="'.$Svlik_blog_url.'/sitemap.xml'.'" target="_blank">'.$Svlik_blog_url.'/sitemap.xml'.'</a>('.$filemtime.')</p>';
echo '<p>添加Sitemap到robots.txt:</p>';
echo '<pre><b>Sitemap: '.$Svlik_blog_url.'/sitemap.xml</b></pre>';
}
$sitemap_html = Svlik_GetHomePath().'sitemap.html'; if(file_exists($sitemap_html)) { echo '<p>检查 Html 静态页面: '; echo '<a href="'.$Svlik_blog_url.'/sitemap.html'.'" target="_blank">'.$Svlik_blog_url.'/sitemap.html'.'</a></p>'; echo '<p>在首页添加此html的链接,方便搜索引擎抓取。'; print '</p>'; }
if(!file_exists($filemipname) && !file_exists($filename) && !file_exists(Svlik_GetHomePath().'sitemap.html')){
echo '<p>你还未设置或者生成任何地图文件!</p>';
}
echo '</div>';
}
function fanly_xml_annotate() {
$blogtime = current_time('mysql');
$xml_author_annotate = '<!-- generated-on="'.$blogtime.'" By Svlik(www.svlik.com) -->';
return $xml_author_annotate;
}
function Svlik_GetTimestampFromMySql($mysqlDateTime) {
list($date, $hours) = explode(' ', $mysqlDateTime);
list($year,$month,$day) = explode('-',$date);
list($hour,$min,$sec) = explode(':',$hours);
return mktime(intval($hour), intval($min), intval($sec), intval($month), intval($day), intval($year));
}
?>
将以上代码按照文件名对应输入之后将会是以下图片效果,然后将整个文件上传至/wp-content/plugins/文件夹内,然后到后台启用插件即可正常使用,再把根目录设置可写即可正常生成了。
如果你不会自己动手,没关系,伸手党可以在底部直接下载即可。
Svlik-SiteMap.zip (下载7711 )



赞赞赞!
2017-12-28 15:15