在wordpress中自动生成站点地图

Auto generate sitemap in wordpress

是否有任何代码可以在 wordpress 自定义主题中自动生成站点地图。 我有一个用 wordpress 构建的博客站点,并为每个页面手动创建了站点地图。

我没有使用插件因为

1.I 不要求在站点地图中列出所有页面

2.Additional 插件会增加我网站的加载时间

现在我需要一个简单的方法(代码)来生成我博客的站点地图。

这是一个简单的代码,您需要将其添加到主题功能文件中,以便在每个博客 posted.Please 时生成站点地图,请参考此 blog 这也可以用于任何自定义插件。

add_action("publish_post", "eg_create_sitemap");

add_action( "save_post", "eg_create_sitemap" );  

function eg_create_sitemap() {

    $postsForSitemap = get_posts( array(
        'numberposts' => -1,
        'orderby'     => 'modified',
        'post_type'   => array( 'post'),
        'order'       => 'DESC'
    ) );
    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap .= "\n" . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";    
    foreach( $postsForSitemap as $post ) {
        setup_postdata( $post );   
        $postdate = explode( " ", $post->post_modified );   
        $sitemap .= "\t" . '<url>' . "\n" .
            "\t\t" . '<loc>' . get_permalink( $post->ID ) . '</loc>' .
            "\n\t\t" . '<lastmod>' . $postdate[0] . '</lastmod>' .
            "\n\t\t" . '<changefreq>monthly</changefreq>' .
            "\n\t" . '</url>' . "\n";
    }     
    $sitemap .= '</urlset>';     
    $fp = fopen( ABSPATH . "sitemap_blog.xml", 'w' );
    fwrite( $fp, $sitemap );
    fclose( $fp );

}