yj-t
2/26/2016 - 6:24 PM

gnSiteMapXML.snippet.php

<?php
/**
 * Based on @garryn Garry Nutting's amazingly fast sitemap generator:
 * http://www.modx360.com/blog/2013/09/03/google-sitemap-thousands-of-resources/
 * 
 * Modified by @sepiariver for multi-context support
 * GPL, no warranties, etc.
 * 
 */

// "300 lives of men I've walked this earth and now I have no time"
ini_set('max_execution_time', 0);

// If no contexts set, only use current one
$contexts = array_filter(array_map('trim', explode(',', $modx->getOption('contexts', $scriptProperties, $modx->context->get('key')))));

// Set cache options
$cacheKey = 'sitemap.' . implode('-', $contexts);
$expires = $modx->getOption('expires', $scriptProperties, 86400);

$options = array(
  xPDO::OPT_CACHE_KEY => 'sitemap',
);

// Fetch from cache
$output = $modx->cacheManager->get($cacheKey, $options);

// If no cached object then query for it
if ($output == null) {
    
    // Set today's date for homepage lastmod
    $today = date('Y-m-d');
    
    // Start document
    $output = '<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    ';
    
    foreach ($contexts as $ctx) {
        
        // Fetch current context object for site_url
        $currentCtx = $modx->getContext($ctx);
        if ($currentCtx) {
            $siteUrl = $currentCtx->getOption('site_url');
            // Add site_url to output
            $output .= "<url><loc>{$siteUrl}</loc><lastmod>{$today}</lastmod></url>" . PHP_EOL;
        } else {
            // We need something to build the links with, even if no context setting
            $siteUrl = $modx->get('site_url');
        }
        
        // Add all resources that meet criteria
        $stmt = $modx->query("
            SELECT
        	    GROUP_CONCAT(
                    '<url>',        
                    CONCAT('<loc>" . $siteUrl . "',uri,'</loc>'),
                    CONCAT('<lastmod>',FROM_UNIXTIME(editedon, '%Y-%m-%d'),'</lastmod>'),
                    '</url>'
                    SEPARATOR ''
                ) AS node
            FROM modx_site_content AS s
            WHERE s.deleted = 0 AND s.published = 1 AND s.searchable = 1 AND context_key='" . $ctx . "'
            GROUP BY s.id
            ORDER BY s.id ASC
        ");
        
        // Add to output
        if ($stmt) {
            $rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
            $output .= implode(PHP_EOL, $rows);
        }
    }
    
    // Wrap up document
    $output .= '</urlset>';

    // Cache for next time
    $modx->cacheManager->set($cacheKey, $output, $expires, $options);
}
// Return
return $output;