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:

Plugin Name: Sitemap
Plugin URI:
Description: Create an XML sitemap
Version: 1.0.0
Author: Satollo
Author URI:
Disclaimer: Use at your own risk. No warranty expressed or implied is provided.

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:

add_action('init', 'sitemap_init');
function sitemap_init()
    // our sitemap code

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:

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

if (isset($_GET['sitemap'])) {
// sitemap generation

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

function sitemap_init()
    if (!isset($_GET['sitemap'])) return;
    // here we proceed with or code

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

function sitemap_init()
    if (!isset($_GET['sitemap'])) return;
    echo "fake sitemap";

All lessons can be found under “sitemap tutorial“.

Leave a Reply