Home > Dev > WordPress SEO > Generate an XML Sitemap

Generate an XML Sitemap

This code generates a simple XML sitemap.

// Add this to your theme's functions.php file

function generate_sitemap() {
    $posts_for_sitemap = get_posts(array(
        'numberposts' => -1,
        'orderby'     => 'modified',
        'post_type'   => array('post', 'page'),
        'order'       => 'DESC'
    ));

    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    foreach ($posts_for_sitemap as $post) {
        setup_postdata($post);

        $postdate = explode(" ", $post->post_modified);
        $sitemap .= '<url>';
        $sitemap .= '<loc>' . get_permalink($post->ID) . '</loc>';
        $sitemap .= '<lastmod>' . $postdate[0] . '</lastmod>';
        $sitemap .= '<changefreq>monthly</changefreq>';
        $sitemap .= '<priority>0.8</priority>';
        $sitemap .= '</url>';
    }

    $sitemap .= '</urlset>';

    $fp = fopen(ABSPATH . "sitemap.xml", 'w');
    fwrite($fp, $sitemap);
    fclose($fp);
}

add_action('publish_post', 'generate_sitemap');
add_action('publish_page', 'generate_sitemap');
Back