It’s time to make this sitemap plugin a little bit more “social”. How? As you learnt in previous lessons, WordPress has hooks that are called to give a way to “others” to make actions (over the default behaviour of WordPress).

There are a lot (really a lot) of these hooks… and now we add one for the sitemap plugin.

Any time a sitemap URL entry is generate by our plugin, our hook lets other plugins to do something related to that entry. An example is a plugin like Global Translator: for each post the plugin is processing, may be there is a translated version in one or more languages. Global Translator can attach to our hook and give us more entries to be added to the sitemap.

From now the code will be more and more complicated and you need to look at the source to better understand the details.

To make this thing to work, and to work in a decent way, many changes need to be done:

  1. I change the way I extract the post from the database: instead of a classic array as seen in the first version, I switch to an associative array
  2. each element extracted from the database will be and associative array with post id and last modified date
  3. before to echo each entry, I complete the associative array representing a post with permalink, change frequency, priority (I build a structure that contains all the infos to creare a sitemap URL entry)
  4. after echoing the sitemap URL entry, we call the hook “sitemap_added”: other plugins can listen to it and do someting (eg. echo other sitemap entries)

The code starts to be a little more tricky. I want to just concentrate on the hook call:

if ($options['hook'])
{
    do_action('sitemap_added', $posts[$i]);
}

the call is already wrapped with a condition check to see if the blog owner activated this integration. Integration like this on can leads to big performance degradation if plugins using sitemap hook are slow.

Just as example, sitemap it self intercept the “sitemap_added” hook and print out a comment in the sitemap after each URL entry.

// second parameter is the fuction name
add_action('sitemap_added', 'sitemap_added');
function sitemap_added($post)
{
    echo '<!-- ' . $post['id'] . '-->';
}

As you see, the function can accept a parameter that will be the post data we build to create a sitemap URL entry. That data is foundamental for other plugins to have, at least, the post id we have processed.

How many hooks we can add to sitemap? This is a list:

  • a way to add something to the sitemap before the plugin URL entries
  • a way to add something to the sitemap after the last entry
  • other?

This new and improved version of sitemap plugin can be download here: [download id=”9″]

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!

0 Comments

Leave a Reply