前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >wordpress站点地图(sitemap)纯代码无需插件自动生成

wordpress站点地图(sitemap)纯代码无需插件自动生成

原创
作者头像
七辰
发布2023-10-04 18:22:43
1K0
发布2023-10-04 18:22:43
举报
文章被收录于专栏:颜汐小屋颜汐小屋

sitemap(xml)网站地图文件是非常关键的,因为这对搜索引擎收录是很有利的。

我们使用wordpress网站时,可以轻松制作出一个站点地图(sitemap),下面说下怎么制作。

第一种方法是利用插件,wordpress的插件非常多,根据自己习惯搜索相应的即可。

第二种是不用插件,纯代码免插件制作站点地图。

用WordPress定时任务去生成sitemap.xml,这样比网上很多方法是在保存、发布文章时生成xml好一些,不会造成处理文章卡的现象。

在WordPress主题文件function.php中添加以下代码:

代码语言:javascript
复制
// 判断定时计划是否存在
if ( ! wp_next_scheduled( 'sitemap_xml' ) ) {
wp_schedule_event( time(), 'twicedaily', 'sitemap_xml' ); // 每天两次
}
add_action( 'sitemap_xml', 'sitemap_xml_func' );

// 定时计划执行函数
function sitemap_xml_func() {
// 获取文章数量
$count_posts = wp_count_posts();
if ( $count_posts ) {
$published_posts = $count_posts->publish;
$sitemap_num = $published_posts / 5000; // 每个xml文件最多包含5000篇文章
$sitemap_num = ceil($sitemap_num);

// 创建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);
}

// 创建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);
}
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
作者已关闭评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档