Generating a sitemap for a custom model
The steps I ended up using were as follows, and the comments and answers so far got me started in the right direction.
First I added a row to the "sitemap" table. Since we have multi-store set up, and because I want to keep my module store agnostic, I didn't hard code this INSERT into a MySQL migration, but just ran it on the store manually:
INSERT INTO sitemap (sitemap_type, sitemap_filename, sitemap_path, store_id)
VALUES ('people', 'people.xml', '/sitemap/', 2);
Then I overwrote the Mage_Sitemap_Model_Sitemap
model inside the global/models section in my own module's config.xml file:
<global>
<models>
<sitemap>
<rewrite>
<sitemap>Mymod_People_Model_Sitemap</sitemap>
</rewrite>
</sitemap>
</models>
</global>
This overwrites any calls to Mage_Sitemap_Model_Sitemap
site-wide with my custom model, but I didn't want to copy and paste too much code there. Using Petar Dzhambazov's suggestion, I used a conditional to defer to the parent class unless the sitemap_type
is "people".
class Mymod_People_Model_Sitemap extends Mage_Sitemap_Model_Sitemap
{
const PAGE_REFRESH_FREQUENCY = 'weekly';
const PAGE_PRIORITY = '1.0';
public function generateXml()
{
if ($this->getSitemapType() != 'people') {
return parent::generateXml();
}
$io = new Varien_Io_File();
$io->setAllowCreateFolders(true);
$io->open(array('path' => $this->getPath()));
if ($io->fileExists($this->getSitemapFilename()) && !$io->isWriteable($this->getSitemapFilename())) {
Mage::throwException(Mage::helper('sitemap')->__('File "%s" cannot be saved. Please, make sure the directory "%s" is writeable by web server.', $this->getSitemapFilename(), $this->getPath()));
}
$io->streamOpen($this->getSitemapFilename());
$io->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
$io->streamWrite('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
$storeId = $this->getStoreId();
$date = Mage::getSingleton('core/date')->gmtDate('Y-m-d');
$baseUrl = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
/**
* Generate people sitemap
*/
$changefreq = Mymod_People_Model_Sitemap::PAGE_REFRESH_FREQUENCY;
$priority = Mymod_People_Model_Sitemap::PAGE_PRIORITY;
$collection = Mage::getModel('people/person')->getCollection();
foreach ($collection as $item) {
$xml = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
htmlspecialchars($item->getUrl()),
$date,
$changefreq,
$priority
);
$io->streamWrite($xml);
}
unset($collection);
$io->streamWrite('</urlset>');
$io->streamClose();
$this->setSitemapTime(Mage::getSingleton('core/date')->gmtDate('Y-m-d H:i:s'));
$this->save();
return $this;
}
}
Is there a better way, that avoids copying and pasting so much from the parent class?