Generating 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 = '';
    $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="" xsi:schemaLocation="" xmlns="">

    foreach($result as $row) {
    $urlset .= '<url>

    echo $urlset;
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:


Final result

site map in xml format

 490 total views

Author: Albert

Leave a Reply