Archive for favicon

anatomy of a new plugin

Update:
Italian translation appended 31 Oct 06

English

Overview

Well I dove deeper into the WordPress documentation since this plugin I wanted to do several things with this one: I wanted it to have an administration panel to enter information, and I did NOT want to make anyone using the plugin have to do anything more than set options through the panel. In other words, no more code tweaking.

Several reasons for that. In the first place, not everyone using WordPress is a geeky hacker like myself. In the second place, it’s annoying even for a geeky hacker like myself to move around themes or update WordPress and have to re-do all the little hacks and edits. So I’m becoming a bigger fan of plug’n'play plugins.

Now to be fair, this isn’t always avoidable. In particular, sidebar elements aren’t easily hooked in (I think this is the idea behind the sidebar widgets project, but I haven’t looked deeply enough into that to be sure). But I’ve already seen some interesting workarounds by other plugin authors and I think it’s possible to avoid many of these problems.

In any case, this plugin is about favicons. Here was my wish list:

  1. To enter an arbitrary image for the favicon
  2. Specify the image relevant to my WordPress directory or as absolute URI
  3. To change it whenever I wanted
  4. To use gif/icon/png files for the favicon
  5. Optionally use it in my rss2 feed
  6. Optionally use it in my atom feed
  7. Everything configurable from the admin panel
  8. A “plug and play” plugin — install and activate, nothing more

To my surprise, this was pretty easy. Perhaps an hour or so of reading the relevant documentation, about 15 minutes coding, another hour or so testing it, and about two hours of writing up and documentation. :-D That’s a pretty typical ratio…

Update: the completed plugin is available at http://www.digitalramble.com/favicon-manager-wordpress-plugin/ (take a peek at the sidebar).

Header Hooks

In order to add something to the headers, without requiring the user to edit their WordPress files, you use


// insert favicon into header using hooks
add_action('wp_head', 'add_favicon_to_headers');

where add_favicon_to_headers is a simple parameterless function that prints out what you want added into the headers. It’s that simple. The first cut at the function does what it’s supposed to do, upon testing:

function add_favicon_to_headers()
{
  $favicon_location="http://example.com/example.ico";
  $favicon_type="x-icon";
  print ' <link rel="icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "\n";
  print ' <link rel="shortcut icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "\n";
}

Of course this is only the first crack at it, just to make sure it works. As it does indeed, if you were to drop the above (encapsulated in the <?php enclosures and with a correct location other than example.ico) into a file with the .php extenstion into your plugin directory. There is in fact a very simple favicon plugin out there that does just that but of course it’s not configurable as per my wish list ;-).

Database

In order to have persistent, retrievable values, I had to make use of the database utilities offered in WordPress. There’s add_option, update_option and get_option for a very simple interface. So I make sure there’s a database entry for the favicon’s location:


// add the saved items to the database if not already there
function favicon_mgr_add_options()
{
        add_option('fm_favicon_location', '');
}

favicon_mgr_add_options();

At this point the database now has a new item with an empty string value for this plugin to use. I tried to use long descriptive names to reduce the possibliity of name space collision. It would have been easier on my fingers to just use “favicon” but of course the possiblity is higher that sooner or later it will run into someone else with the same brilliant idea.

This means that the hook should now retrieve the value from the database:


function add_favicon_to_headers()
{
  $favicon_location=get_option('fm_favicon_location');
  $favicon_type=get_favicon_type($favicon_location);
  print ' <link rel="icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "\n";
  print ' <link rel="shortcut icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "\n";
}

Now you see why I used variables to begin with :). The get_favicon_type is another function I wrote (but didn’t include for clarity above) that returns the correct type (x-icon, gif, jpg, png) depending on the favicon’s name. So now I’m set regardless of what the user enters (I do need to add a check in case the extension is unknown, but again I’m keeping things as short as I can).

Admin panel

Wordpress also provides a pretty straightforward set of functions for creating an admin panel. It was actually pretty easy. First there’s the hook to put a new menu item under Options (you can do more, but for basic stuff like this, Option’s fine).


// create hook for new submenu
add_action('admin_menu', 'favicon_mgr_admin_menu');

// title of page, name of option in menu bar, which function lays out the html
function favicon_mgr_admin_menu()
{
        add_options_page(__('Favicon Manager Options'), __('Favicons'), 5, basename(__FILE__), 'favicon_mgr_options_page');
}

// html layout for option page, plus detection/update on new settings
function favicon_mgr_options_page()
{
  ...
}

So what this all does is first a menu item is added in. The menu item in turn specifies the function that lays out its page. So then that function prints out the html necessary to allow input, etc. That page will also have to update the database entries so that the header hook retrieves the correct value to drop into the headers. So it’s starting to come together. Here’s the first cut at the options page:


function favicon_mgr_options_page()
{
        $updated = false;

        if (isset($_POST['fm_favicon_location']))
        {
                $fm_favicon_location = $_POST['fm_favicon_location'];
                update_option('fm_favicon_location', $fm_favicon_location);
                $updated = true;
        }
        $fm_favicon_location = get_option('fm_favicon_location');
        if ($updated)
        {
                ?>
                <div class="updated"><p><strong>Options saved.</strong></p></div>
                <?php
        }


Let’s take the pause that refreshes. Remember that this page can be used when the user first enters the option page, or after they’ve hit the submit button. So the first thing to check is to see if this is on submission. isset provides a way of checking to see if that form input element has been set or not. If it has, I drop it into the database, and set update to true.

        ?>
        <div class="wrap">
                <h2>Favicon Settings</h2>
                <form name="form1" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">

                        <fieldset class="options">

                                <legend>Favicon in WordPress Pages</legend>
                                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                                <tr valign="top">
                                        <th width="33%" scope="row">Location:</th>
                                        <td><input name="fm_favicon_location" type="text" width="60" value="<?php echo $fm_favicon_location; ?>"/>
                                        </td>
                                </tr>
                                </table>

                        </fieldset>

                        <p class="submit">
                          <input type="submit" name="Submit" value="Update Options &raquo;" />
                        </p>
                </form>

        </div>

        <? php
}

This part prints out the actual form page, with values in the input field if any exist. The layout is already controlled via the stylesheets and classes used here, so the familiar blue and white theme layout comes right up.

That’s it! Pretty much the only items left are the arbitrary or relative locations for the favicon (I want the users to be able to enter the location either way) and the RSS2/Atom options. The former is easily resolved with one more function:

And now I update instances where I get the favicon_location to run the results through this before using it. I do not use this before storing the location into the database, though. To avoid user confusion, I prefer to retain what they actually entered.

The Feed Options

I’m only going to describe the RSS2 additions here. The Atom is exactly the same other than the actual output in the hook.

As of WordPress 2.0, hooks are provided for RSS2:


function add_image_to_rss2_feed()
{
  // do this or not depending on user settings in panel!
  if (get_option('fm_rss2_feed_option')=="Y")
  {
        $favicon_location=create_favicon_uri(get_option('fm_favicon_location'));
        echo "<image>\n";
        echo "  <link>". get_bloginfo_rss('url') ."</link>\n";
        echo "  <url>". $favicon_location ."</url>\n";
        echo "  <title>". get_bloginfo_rss('name') ."</title>\n";
        echo "</image>\n";
  }
}

// insert image into rss2 feed
add_action('rss2_head', 'add_image_to_rss2_feed');

So now I add it to my database:

// add the saved items to the database if not already there
function favicon_mgr_add_options()
{
        add_option('fm_favicon_location', '');
        add_option('fm_rss2_feed_option', '');
}

This gets added to the option page function before printing out whether or not new options have been saved:

        // checkboxes flip on/off
        if ($_POST['fm_rss2_feed_option']!=get_option('fm_rss2_feed_option'))
        {
                $fm_rss2_feed_option = $_POST['fm_rss2_feed_option'];
                update_option('fm_rss2_feed_option', $fm_rss2_feed_option);
                $updated = true;
        }
        $fm_rss2_feed_option = get_option('fm_rss2_feed_option');

The checkboxes work a little bit differently than text input boxes. If you uncheck a checkbox, you do NOT get input. Since this is an on/off switch, the fix is to simple check if the value is the same as what is stored since only two values are possible.

Now I add in the bit of HTML to ask the user to check off whether they want the favicon added to their RSS2 feed:


                                <legend>Images in Feeds</legend>
                                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                                <tr valign="top">
                                        <th width="33%" scope="row">Add to RSS2 Feed?</th>
                                        <td><input name="fm_rss2_feed_option" type="checkbox" value="Y" <?php if ($fm_rss2_feed_option=="Y") echo "checked"; ?> >
                                        </td>
                                </tr>
                                </table>

This is put into the fieldset wrapper of the options page.

Atom is identical, but the image is added through an &lt;icon&gt; marker and the value is simply the location of the favicon.

The feed images are handled a little differently from the header favicons. They don’t actually have to be 16×16, they can be a little bit larger. Traditionally they appear along the header field in an aggregator, and if you look at a wunderground.com weather feed in Bloglines, you’ll notice a relatively large rainstorm/weather icon at the top of its articles. But (using Bloglines for reference again), the images can also be used on the left in Blogline’s “bookmarks” tree. It may be worthwhile giving an optional image field for the feeds: if it’s left empty use the favicon, otherwise use the image for the feeds only. I haven’t decided…

Support Files

Although the code is written up and tested, I’m not yet finished. I need to put together a couple more things:

  • A readme.txt file to be bundled with the favicon manager php file
  • A zipped version with the correct directory, etc to be put out in the public directory
  • A help/support page where potential users can read about the plugin, find directions for installing, and find the bundle itself

There’s a few other more optional actions to take as well, such as whether to register the plugin with Codex, WP Plugins Database, and other forums that collect plugin info.

Some Thoughts

I might be able to make this plugin work for earlier versions of WordPress by protecting the feed options with a check for the existence of the feed hooks. If they’re not there, then skip all the feed elements. Thus the plugin would degrade to favicons-in-headers-only mode, provided none of the other function calls or hooks have changed substantially. But given that I have written this well after the 2.0 upgrade, I’m not particularly inclined to do this…especially since I don’t have the means for testing it anyway.

Italian

Panoramica

Ho scavato più in profondità nella documentazione di WordPress, perchè volevo che il mio plugin rispettasse alcuni criteri: volevo che avesse un pannello di amministrazione perchè NON volevo che chiunque lo usasse fosse obbligato a fare altro che impostare opzioni tramite il pannello. In altre parole, basta modifiche al codice.

Diverse ragioni per questo. Primo, non tutti gli utenti WordPress sono smanettoni come me. Secondo, è noioso anche per gli smanettoni come me cambiare temi o aggiornare WordPress e dover riapplicare tutte le piccole modifiche. Per questo motivo sto diventando la più grande fan dei plugin plug’n’play.

Per essere onesti, non sempre questo è evitabile. In particolare, gli elementi delle barre laterali non sono facilmente integrabili (credo sia questa l’idea alle spalle dei widget, ma non ho ancora approfondito abbastanza da esserne certa). In ogni caso ho già visto diversi metodi interessanti nel lavoro di altri autori di plugin, e credo sia possibile evitare molti di questi problemi.

Comunque sia, questo plugin riguarda le favicons. Questa era la mia lista dei desideri:

  1. Poter inserire una immagine arbitraria come favicon
  2. Poter specificare l’immagine rilevante nella mia cartella WordPress anzichè come URI assoluta.
  3. Poter modificare questa immagine in qualunque momento.
  4. Poter usare files gif/icon/png per la favicon
  5. Eventualmente usare l’immagine nel mio feed rss2
  6. Eventualmente usare l’immagine nel mio feed atom
  7. Tutto questo configurabile nel pannello di amministrazione
  8. Un plugin “plug and play” – da installare e attivare, null’altro.

Con mia sorpresa, questo è stato abbastanza semplice. Più o meno un ora per leggere la documentazione rilevante, circa 15 minuti per programmare, un’altra ora per il collaudo, e quasi due ore di scrittura e documentazione :-D Questa è un proporzione abbastanza tipica…

Il plugin completo è disponibile all’indirizzo
http://www.digitalramble.com/favicon-manager-wordpress-plugin/
(date un’occhiata sul lato).

Agganci agli header

Per aggiungere qualcosa agli header, senza obbligare l’utente a modificare i propri files di WordPress, potete usare


// insert favicon into header using hooks
add_action('wp_head', 'add_favicon_to_headers');

dove add_favicon_to_headers è una semplice funzione senza parametri che inserisce ciò che volete all’interno degli header. E’ molto semplice. La prima bozza della funzione è in grado di fare ciò che vorremmo facesse, durante i test:


function add_favicon_to_headers()
{
  $favicon_location="http://example.com/example.ico";
  $favicon_type="x-icon";
  print ' <link rel="icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "n";
  print ' <link rel="shortcut icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "n";
}

Ovviamente questa è solo una prima stesura, giusto per essere certi che funzioni. E può funzionare, se inserite il codice qui sopra (all’interno dei codici ?php e con un indirizzo corretto al posto di example.ico) in un file con estensione .php nella vostra cartella dei plugin. Esiste infatti un semplice favicon plugin che fa esattamente questo ma non è configurabile come ho detto nella mia lista dei desideri ;-)

Database

Per avere valori persistenti e recuperabili, ho dovuto fare uso delle utilità a livello database offerte in WordPress. Ci sono add_option, update_option e get_option per un interfacciamento semplice. Quindi farò in modo di verificare che sia presente un dato nel database con l’indirizzo della favicon:


// add the saved items to the database if not already there
function favicon_mgr_add_options()
{
        add_option('fm_favicon_location', '');
}

favicon_mgr_add_options();

A questo punto il database ha ora un nuovo elemento, con un valore vuoto (una stringa di testo) disponibile per questo plugin. Ho provato a usare nomi lunghi e descrittivi (nelle funzioni, N.d.T.) per ridurre l’eventualità di una collisione di name space. Sarebbe stato più semplice per le mie dita usare solo “favicon”, ma ovviamente sarebbe stata più alta la possibilità che qualcuno abbia avuto prima o poi la mia stessa brillante idea.

Questo significa che l’aggancio ora può recuperare valori dal database:


function add_favicon_to_headers()
{
  $favicon_location=get_option('fm_favicon_location');
  $favicon_type=get_favicon_type($favicon_location);
  print ' <link rel="icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "n";
  print ' <link rel="shortcut icon" href="'. $favicon_location .'" type="image/'. $favicon_type .'" />';
  print "n";
}

Ora potete vedere perchè ho usato le variabili fino ad ora :-). La funzione get_favicon_type è un’altra funzione che ho scritto (e non ho incluso sopra per chiarezza) che restituisce il tipo corretto (x-icon, gif, jpg, png) a seconda del nome della favicon. In questo modo la funzione è pronta qualunque sia l’input dell’utente (dovrei aggiungere un controllo nel caso l’estensione sia sconosciuta, ma ancora una volta sto cercando di rendere le cose più semplici possibile).

Pannello di amministrazione

WordPress offre anche un set diretto di funzioni per crare un pannello di amministrazione. E’ stato decisamente semplice. Per prima cosa è presente un aggancio per inserire un nuovo menù sotto il menu Opzioni (potete fare anche altro, ma per cose basilari come queste, Opzioni è più che sufficiente).


// create hook for new submenu
add_action('admin_menu', 'favicon_mgr_admin_menu');

// title of page, name of option in menu bar, which function lays out the html
function favicon_mgr_admin_menu()
{
        add_options_page(__('Favicon Manager Options'), __('Favicons'), 5, basename(__FILE__), 'favicon_mgr_options_page');
}

// html layout for option page, plus detection/update on new settings
function favicon_mgr_options_page()
{
  ...
}

Quindi, tutto ciò che questo produce è l’inserimento di un oggetto menu. L’oggetto specifica a sua volta la funzione che definirà la pagina. Quindi, la funzione inserirà il codice necessario a permettere gli input e il resto. Questa pagina dovrà inoltre poter aggiornare i record nel database in modo che gli agganci della testata possano ricevere i valori corretti da inserire nella stessa. In questo modo le cose iniziano a essere collegate. Una prima stesura della pagina di opzioni:


function favicon_mgr_options_page()
{
        $updated = false;

        if (isset($_POST['fm_favicon_location']))
        {
                $fm_favicon_location = $_POST['fm_favicon_location'];
                update_option('fm_favicon_location', $fm_favicon_location);
                $updated = true;
        }
        $fm_favicon_location = get_option('fm_favicon_location');
        if ($updated)
        {
                ?>
                <div class="updated">
<strong>Options saved.</strong></div>
                <?php
        }

Prendiamo una pausa rinfrescante. Ricordiamoci che questa pagina verrà mostrata solo quando l’utente entrerà nella pagina di opzioni, oppure dopo aver modificato le opzioni stesse. Quindi la prima cosa da verificare è se l’elemento input del modulo è stato modificato o meno. Nel primo caso, verrà inserito nel database, e verrà impostato update su true.


        ?>
        <div class="wrap">
                <h2>Favicon Settings</h2>
                <form name="form1" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">

                        <fieldset class="options">

                                <legend>Favicon in WordPress Pages</legend>
                                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                                <tr valign="top">
                                        <th width="33%" scope="row">Location:</th>
                                        <td><input name="fm_favicon_location" type="text" width="60" value="<?php echo $fm_favicon_location; ?>"/>
                                        </td>
                                </tr>
                                </table>

                        </fieldset>

                        <p class="submit">
                          <input type="submit" name="Submit" value="Update Options &raquo;" />

                </form>

        </div>
        <? php

Questa parte restituisce la pagina del modulo, con i valori nel campo imput se sono già impostati. La presentazione è già controllata tramite i fogli di stile e le classi usate, quindi verrà usato il familiare tema bianco e blu.

E’ tutto qui! In pratica gli unici elementi non inseriti sono la posizione abitraria o relativa della favicon (voglio che gli utenti abbiano la possibilità di inserire entrambe) e l’opzione RSS2/Atom. La prima è risolta facilmente con una ulteriore funzione:

Ora aggiornerò le istanze in cui richiamo $favicon_location per processare i risultati tramite questa funzione prima di usarli. Non userò comunque questa funzione prima di memorizzare la posizione nel database. Per evitare confusioni da parte dell’utente, preferisco tenere ciò che hanno inserito.

L’opzione Feed

Spiegherò solamente l’aggiunta per RSS, in quanto l’opzione Atom è identica, eccetto l’output nell’aggancio.

A partire da WordPress 2.0, sono forniti agganci per gli RSS2:


function add_image_to_rss2_feed()
{
  // do this or not depending on user settings in panel!
  if (get_option('fm_rss2_feed_option')=="Y")
  {
        $favicon_location=create_favicon_uri(get_option('fm_favicon_location'));
        echo "<image>n";
        echo "  <link>". get_bloginfo_rss('url') ."</link>n";
        echo "  <url>". $favicon_location ."</url>n";
        echo "  <title>". get_bloginfo_rss('name') ."</title>n";
        echo "</image>n";
  }
}

// insert image into rss2 feed
add_action('rss2_head', 'add_image_to_rss2_feed');

Quindi inserirò nel mio database:


// add the saved items to the database if not already there
function favicon_mgr_add_options()
{
        add_option('fm_favicon_location', '');
        add_option('fm_rss2_feed_option', '');
}

Questo verrà aggiunto alla pagina di opzioni prima dell’output, a prescindere dal fatto che le nuove opzioni siano già salvate.


        // checkboxes flip on/off
        if ($_POST['fm_rss2_feed_option']!=get_option('fm_rss2_feed_option'))
        {
                $fm_rss2_feed_option = $_POST['fm_rss2_feed_option'];
                update_option('fm_rss2_feed_option', $fm_rss2_feed_option);
                $updated = true;
        }
        $fm_rss2_feed_option = get_option('fm_rss2_feed_option');

Le caselle di selezione funzionano in modo leggermente differente dai campi di input testuale. Se deselezionate una casella, NON avrete un input. Dal momento che è un selettore acceso/spento, la soluzione è controllare se il valore è lo stesso di quello memorizzato, dal momento che solo due valori sono possibili.

Ora aggiungerò del codice HTML per chiedere all’utente di scegliere se usare la favicon nei propri feed RSS2:


                               <legend>Images in Feeds</legend>
                                <table width="100%" cellspacing="2" cellpadding="5" class="editform">
                                <tr valign="top">
                                        <th width="33%" scope="row">Add to RSS2 Feed?</th>
                                        <td><input name="fm_rss2_feed_option" type="checkbox" value="Y" <?php if ($fm_rss2_feed_option=="Y") echo "checked"; ?> >
                                        </td>
                                </tr>
                                </table>

Questo è inserito nel contenitore fieldset della pagina di opzioni.

Atom è identico, ma l’immagine è inserita tramite un tag e il valore è semplicemente l’indirizzo della favicon.

Le immagini dei feed sono gestite in modo differente dalle favicon della testata. Non devono essere per forza 16×16, ma possono essere un po’ più grandi. Di solito appaiono accanto al campo della testata in un aggregatore, e se date un’occhiata al feed delle previsioni del tempo su Bloglines, potrete notare una icona relativamente grande in cima ai suoi articoli. Ma (usando per esempio ancor Bloglines), le immagini possono anche essere usate sulla destra, nei bookmarks di Bloglines (le informazioni su Bloglines possono essere variate, N.d.T. ). Può valere la pena offrire un campo opzionale per l’immagine dei feed: se è lasciato vuoto verrà usata la favicon, altrimenti verrà usata questa immagine solo per i feed. Non ho ancora deciso…

Files di supporto

Anche se il codice è scritto e collaudato, non ho ancora finito. Devo aggiungere a questo alcune cose:

* Un file readme.txt da allegare con il file php del plugin
* Una versione compressa con le cartelle e i files corretti da mettere nella mia cartella pubblica
* Una pagina di aiuto e supporto dove i potenziali utenti potranno trovare informazioni sul plugin, istruzioni per l’installazione, e dove sarà disponibile l’archivio stesso.

Ci sono alcune azioni facoltative che potreste voler intraprendere, come registrare il plugin su Codex, nel database dei plugin WP, e in altri forum che raccolgono informazioni sui plugin.

Alcuni pensieri

Potrei essere in grado di rendere questo plugin funzionante con versioni precedenti di WordPress, proteggendo l’opzione dei feed con un controllo sulll’esistenza dell’aggancio ai feed. Se non è presente, allora evita tutti gli elementi feed. In questo modo il plugin dovrebbe degradare in modalità favicon-solo-header, tenendo conto che nessuna delle altre funzioni è stata modificata. Ma dato che ho scritto questo ben dopo l’aggiornamento alla versione 2.0, non sono particolarmente invogliata a farlo… specialmente visto che non ho i mezzi necessari per fare i test.

del.icio.us:anatomy of a new plugin  digg:anatomy of a new plugin

Comments (19)

examining rss feeds

In bloglines, I notice some subscriptions have either their favicons appear on the subscription link (for example, any blog powered by Blogger), or have a small graphic that appears in the header (for example, wunderground.com’s weather channels). My DR subscription, though, doesn’t show any icons or graphics. This therefore has to be something that’s being sent by the feed.

Feeds come in three basic flavors these days — as I understand it, Atom is the newest kid on the block, the most widely used is probably RSS 2.0, and RSS 1 is still used by a few places but largely deprecated in favor of RSS 2. I found all the usual disagreements over which was the best, which would be most easily extensible in the future and so on and so forth. In the end, though it seems to me that much of the time a site will offer both Atom and RSS2.

Atom and RSS 2 provide a means to package up a site (an HTML page) into an XML representation which can then be used by a feed reader and/or aggregator, to put up the info about the site into the aggregator/feed reader. If you use Bloglines (or Google Reader, or any of a dozen other similar programs out there), that XML is what they’re using to snag info from your subscriptions. These programs will query your subscription sites regularly for any updates and download those into your reader.

To see your own WordPress atom and rss2 feeds, add feed/atom to your WordPress blog address, and just feed for rss2. So for example, DR’s RSS2 feed is at http://www.digitalramble.com/feed and it’s atom feed at http://www.digitalramble.com/feed/atom. Note that to see the atom feed, you’ll have to save it to a file and open it with a text editor (browsers do not “recognize” Atom pages yet.)

In tracking down the feeds for these examples, I found XML descriptors of the format channel->description->image->url and the url’s would be the locations of the images being used. Obviously, my own feed generators are not doing this, because even though I jumped through all the hoops to get favicons up for my site, they’re not showing up in a Bloglines subscription.

I, of course, must fix this.

So WordPress generates two feeds in a basic setup (at least, basic here at DreamHost?). I have three relevant files in my top wordpress directory: wp-atom.php, wp-rss.php, and wp-rss2.php. Because RSS 2’s so popular, let’s look at that one first. There’s a RSS 2 specification here. So as an experiment, I edit the wp-rss2.php file to contain


<image>
<link>http://digitalramble.com/</link>
<url>http://digitalramble/wordpress/favinit.gif</url>
<title>Digital Ramble</title>
</image>

Of course once I get into the php file and look around, I change this to use the same php bloginfo to genericize it:

        <image>
                <link><?php bloginfo_rss('url') ?></link>
                <url><?php echo get_option('siteurl'); ?>/favinit.gif</url>
                <title><?php bloginfo_rss('name'); ?></title>
        </image>

This isn’t perfectly ideal of course. Seems like there should be a favicon per theme, which loads in with the theme, and updates the icon in the browser tabs, bookmarks, and feeds. As it is, I’ve only got one favicon installed, and if I change things around I would have to change the current theme’s header.php, and the wp-content’s atom/rss generators.

Maybe I should make this a plugin, for the experience of creating an addition to the Dashboard, where you can enter your favicon, and then add the appropriate calls in your atom/rss2 feeds and your header…hmmm not a bad idea. Not today though :) This is just proof of concept.

OK, onto Atom. Googling around, I find its specification here. In scanning down this file, I find the relevant item: atom:icon about half way down the text. This looks like it. Here’s what it says:

The “atom:icon” element’s content is an IRI reference [RFC3987] that identifies an image that provides iconic visual identification for a feed.


atomIcon = element atom:icon {
   atomCommonAttributes,
   (atomUri)
}

The image SHOULD have an aspect ratio of one (horizontal) to one (vertical) and SHOULD be suitable for presentation at a small size.

There’s also atom:logo which is almost the same, except for a 2:1 horizontal:vertical aspect ratio. OK, so after some tinkering around, I decide on adding:


<icon><?php echo get_option('siteurl'); ?>/favinit.gif"</icon>

I’m not as certain of this one, because the atom feeds I was able to look at, on sites that have icons showing (such as DistroWatch), don’t seem to contain any icon information in their atom description! I did come across some comments that some aggregator sites will just pull the favicons from the feeding sites (but in that case the favicon.ico I have in my root directory should show up, unless that’s not really the root directory, which could well be the case…)

Now to publish this so I can see the results if any in Bloglines…!

del.icio.us:examining rss feeds  digg:examining rss feeds

Comments

lazy saturday fun with favicons

It’s interesting just how useful a really good favicon is. I wound up putting one in for this one, because I was going crazy locating it among all the other plain-folded-page default favicons in my tabs. I typically have dozens of tabs going in a Firefox session. I started out first with that little curlique thing that comes with the original default template (I’m going to modify it to a point where I’ll probably have to rename the theme to avoid confusion :-O ) but I decided it wasn’t really that identifiable or memorable. If I scan my tabs there are several that I can see at a glance. Delicious is readily identifiable as is Gmail, LiveJournal, Bloglines, Blogger (it’s ugly but it totally jumps out), Google (but Google calendar isn’t that great), Technorati and so on. So when I switched to the more floral style header above, I tried using one of the flowers…but it renders down into a rather indistinguishable blob. So I gave up and just used the DR initials, using the same font as in the name above, and I think that works out pretty well.

For the SCLRR website, I tried miniaturizing the little dog in their logo but again blobbiness was the general result. My coworker thought it was a fellow smoking his pipe. Sigh. So I just found a small cartoon bone on the ‘net and shrunk that down, and I think that works pretty well. I may transparent the green out, but for the moment I’m letting it be.

But wait! Why stop now?! I’ve resurrected another old site of mine, that I took down because back in the day several gigs of bandwidth were too expensive to pay for (I now get ten times the bandwidth for a fraction of the price; go figure). Now this site is a throwback to 1995 era websites (so no giggling), but I’ve at least started it off with a new favicon, and will be cleaning this site up as well.

del.icio.us:lazy saturday fun with favicons  digg:lazy saturday fun with favicons

Comments (2)

scattered bits and pieces

Need to redo the favicon part: I notice that every time I navigate away from the basic home page (for example, choosing “about” or one of the available categories) I lose the favicon. This is certainly because I put in a plain file name. I’d like to use a relative file name, or the php stored domain name to avoid hardcoding in a file.

I changed the date format to a more suitably geeky year-month-day format. That was found in the index.php and in the single.php files of the themes directory, which would no doubt be dependent on which theme one was using. I note, by the way, that this particular theme I’ve started off with overrides the date format that can be set in the WordPress Dashboard.

I’d like to add in support for technorati and delicious tags. I’ve found this page which discusses an extensive tag plugin “Ultimate Tag Warrior“. I’d like a tag cloud; I’ve implemented that elsewhere (LiveJournal, Component style) and it’s fun to have. There seem to be a few more related plugins, but this seems to have a bit of everything.

Lessee, download, unzip…mumble, mumble…okay looks like there’s lots of little bits and stuff in separate directories. So in the plugins directory, I’ll just create a softlink into the UTW’s plugin directory so I can keep all the files in one place. Which looks like it works just fine. I get three new items in the plugins: UTW, UTW legacy, and UTW archive. So I’ll activate the first one.

As promised, there’s a new “tag” option under the Manage panel. Just trying for basic stuff now, so I’ve only made simple choices. Now I’ve added

Argh. This editor stinks. It will NOT post html here as code. Gah. Time to reset some options, I think.

del.icio.us:scattered bits and pieces  digg:scattered bits and pieces

Comments

moseying around with favicon

…and look where it took me!

Looking at the blog, of course I decided I needed a favicon because I open entirely too many tabs in my browser, and the featureless little default of a blank page just fades away & makes it hard for me to find the right tab. (I wish all pages put out favicons.)

Googling on favicon I found this Wiki entry that details how to do this. Given the history of the favicon, there’s multiple ways to specify the favicon. The simplest is the mere presence of a file named favicon.ico although of course for many reasons that’s a horrible way to implement things. Still, I put one together as a gif file and used one of the free converters also listed on the wiki page, just to test it out quickly.

Looks like the ico format doesn’t support transparency, or at least the converter I used doesn’t. In any case, I wanted to use the more standard (and flexible) link format so that I can use other graphics such as gif or png.

However, this now entailed modifications to the head tag and of course since this is in WordPress, I don’t have a simple .html file but rather a series of php cgi scripts. With some digging and some perusal of WordPress’ support pages I found the relevant files in the themes directory, under (of course) header.php.

So this means any time I change my theme, I’ll need to migrate this modification over. Hmm. I already plan to make my own theme anyway, but this sounds annoying for anyone who just uses ready-made templates.

del.icio.us:moseying around with favicon  digg:moseying around with favicon

Comments

Bad Behavior has blocked 453 access attempts in the last 7 days.