Tutorial: Write a Sitemap Plugin Day 2

Now we have a clear idea of the final product, so we can start to structure the plugin. Opsss, and the name? It can sound incredible but on the WordPress Plugin Directory the name “sitemap” is available.

So our plugin will be named “sitemap”.

Let’s start creating a folder named “sitemap” and the file “plugin.php” inside it. I’m used to call the main plugin file “plugin.php” it’s clear to understand (in a plugin there will be more than one php file). Surely, if you’re working with an IDE (like NetBeans) on more than one plugin, this name can create confusion (if you are a new by programmer…).

Every plugin for WordPress has to start with a piece of PHP comment that contains the plugin name and other infos that let WordPress to recognize it as a valid plugin. This is our:

Now we have to start to work with WordPress hooks (called actions). In this plugin we intercept the plugin initialization and on this step we look if there is a request with sitemap within the parameters. If so we produce and echo the xml sitemap and stop so WordPress doesn’t elaborate further the request.

To intercept the initialization the code is really simple:

as you see the add_action call register our function “sitemap_init” and “ask” WordPress to call it on initialization process (“init” hook).

To make the function names unique, we prefix all function name and global variable with “sitemap_”.

Now, how can we check if the sitemap parameter is present and we have to do something? As we stated on the plugin functionalities, the sitemap has to be generated when someont call this URL:

http://www.satollo.net/?sitemap=xml

To check if the parameter “sitemap” has been specified, this is the code:

I prefer to write functions starting with a set of condition to know if the function has to continue or not:

Just to test it, we add a fake sitemap echoing:

All lessons can be found under “sitemap tutorial“.

My excuses for my bad english but it's the only way I have to communicate with you. Would you suggest a correction? Leave a comment, thank you!

Leave a Reply