Categories
Tutorials

Tutorial: Write a Sitemap Plugin Day 4

We are at the end. At least the last day to have the plugin really working. After this lesson, I will start a new series to add some features to this plugin (control panel, options, integration with other plugins).

The last step is to print out XML elements that represent each single URL of our blog posts. On first lesson I showed up the XML format of those entries:

<url>
      <loc>http://www.example.com/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
</url>

Print them is incredible simple, just a “for” cycle:

$c = count($posts);
for ($i=0; $i<$c; $i++)
{
    echo "<url>n";
    echo "<loc>" . get_permalink($posts[$i][0]) . "</loc>n";
    echo "<lastmod>" . substr($posts[$i][1], 0, 10) . "</lastmod>n";
    echo "<changefreq>monthly</changefreq>n";
    echo "<priority>0.8</priority>n";
    echo "</url>n";
}

I buld the permalink (the post URL) with a WordPress function (get_permalink) which can be called with a post id as parameter.

The last modified date is a piece of the date from the database (we are lucky, WordPress uses MySQL which return the date already formatted for a sitemap. I only need to strip away the time part).

I do not have any information to compute the change frequency and the priority, so I write them with fixed values.

A sitemap is a way to send to Google (or other search engine) a list of URL to download, scan and index. Usually the home page of a blog or a site is the first page indexed by search engines, so adding it to the sitemap seems not really useful.

So why to add it? The home page is a page that changes frequently, and search engines loves things that change. The sitemap protocol let us to specify a “last modified date”, hence we can add the home page URL to the sitemap setting the last change to “today”.

Here the code:

    echo "<url>n";
    echo "<loc>" . get_option('home') . "/</loc>n";
    echo "<lastmod>" . date('Y-m-d') . "</lastmod>n";
    echo "<changefreq>daily</changefreq>n";
    echo "<priority>1</priority>n";
    echo "</url>n";

That’s all, folks! And now you can download this first version of the plugin: [download id=”8″].

All lessons can be found under “sitemap tutorial

Leave a Reply