在WordPress中,生成和自动更新站点地图(sitemap)是一个常见的需求,因为这对搜索引擎优化(SEO)至关重要。WordPress本身并不直接内置一个自动更新sitemap的功能,但你可以通过插件来实现这一功能。然而,如果你想要了解如何通过PHP代码手动或定制化地生成和自动更新sitemap,下面是一个基本的思路和一些代码示例。
思路
- 创建sitemap.xml文件:你可以在你的WordPress主题目录或插件目录中创建一个
sitemap.xml
文件。但是,更常见的做法是使用一个PHP脚本来动态生成sitemap。 - 编写PHP脚本来生成sitemap:这个脚本需要查询WordPress数据库,获取所有文章、页面、分类、标签等的URL,并根据SEO最佳实践生成sitemap。
- 自动更新sitemap:你可以通过WordPress的钩子(Hooks)功能,在每次内容更新时自动更新sitemap。这通常涉及到使用
wp_insert_post
、save_post
等动作钩子。 - 确保sitemap可访问:确保你的
.htaccess
文件或服务器配置允许直接访问sitemap.xml(如果你的sitemap是通过URL访问的PHP脚本生成的)。
说明
wordpress sitemap生成PHP,可以自动更新stiemap
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 xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">'
?>
<!-- generated-on=<?php echo get_lastpostdate('blog'); ?> By 派克资源-->
<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>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END