Writing XML SiteMap

Generating XML SiteMap

Search engine robots require sitemap in pure XML format, without any additional content, header, or footer. But WordPress plugin is just for content, when the shortcode being used in pages or posts it will be added with header, menu, and footer automatically.

In order to generate pure XML we need to control the output. Using ob_ (output buffer) functions we can achieve this goal, exit() function ignores all following outputs.

1. Add ob_start() to top of header.php file under child theme root folder.

2. Add plugin function to generate sitemap in xml format.

function sitemap_post_shortcode($atts) {
    global $wpdb;

    $baseurl = 'https://211cn.ca';
    $sql = "SELECT concat('$baseurl/',year(post_date),'/',month(post_date),'/',post_name) url ,post_modified from wp_posts WHERE post_type='post' and post_status='publish' order by post_modified DESC";
    $result = $wpdb->get_results($sql);

    $doc = '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="'. $baseurl .'/wp-content/plugins/albert/sitemap.xsl"?>
<!-- generated-on="'. date("Y-m-d\TH:i:s+00:00") .'" -->
';
    $urlset = $doc.'<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">
';

    foreach($result as $row) {
    $urlset .= '<url>
        <loc>'.$row->url.'</loc>
        <lastmod>'.date('Y-m-d\TH:i:s+00:00',strtotime($row->post_modified)).'</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.3</priority>
    </url>';
    }
    $urlset.="
</urlset>";

    ob_clean();
    echo $urlset;
    ob_flush();
    exit();
}
add_shortcode('211postmap', 'sitemap_post_shortcode');

Note that the date in <lastmod> element is required in this format: <lastmod>2019-04-10T11:22:33+00:00</lastmod>, using this code to convert:

date('Y-m-d\TH:i:s+00:00',strtotime($row-&gt;post_modified))

Final result

site map in xml format

293 total views, 1 views today

Author: Albert

Leave a Reply