nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Using the DeviceAtlas API with WordPress

Over the past couple of weeks I’ve had the absolute pleasure (no not really!) of adapting a WordPress site and making it accessible on as many mobile phones as possible. Now I must admit I’ve not had much experience building mobile sites so this is all new ground for me; and by mobile website I don’t mean for the iPhone only (for more information on this plus lots of swear words see ‘The iPhone Obsession‘ by PPK).

Luckily there are already many plug-ins available for WordPress that can get you started on your way, one that really grabbed my attention was ‘WordPress Mobile Pack‘ by MobiForge. The plug-in contains a mobile optimised theme that you can adapt for your needs and the ‘mobile switcher’ functionality. Mobile switcher detects if a user is browsing from a desktop or a mobile phone and switched the theme accordingly. Great, we’re already half way there!

One of the specifications for the site was that it must work on a set of 4 different screen widths (480px, 320px, 240px and 176px) and this is where the DeviceAtlas API comes in very useful. Device Atlas keep a huge database of mobile phone user agent strings plus specifications associated with a particular mobile phone that you can tap into and use in your web application.

Now one thing I must mention is that according to the mobiForge page listed above, WordPress Mobile Pack includes DeviceAtlas integration. This turns out not to be the case. I couldn’t find any settings regarding DeviceAtlas in the plug-in admin area and very little mentioned on the forums. I assume the page hasn’t been updated for a while and the functionality has been removed. This isn’t a problem though as it’s fairly simple to integrate the DeviceAtlas API into your PHP application i.e. WordPress. Here’s how you do it.

First you must register with DeviceAtlas and order a developer licence (there’s a free option available here). Once registered grab a copy of the PHP API and the latest Device JSON file (under ‘My account’). Unpack the API into the root of your web application (or wherever you like, just make sure the includes are set correctly) and copy the JSON file into the json directory along side it. You are now ready to include the API into the base WordPress Mobile Pack theme. Copy and paste the following into your header.php above the doctype:

1
2
3
4
5
6
7
8
<?php
//Include the DA API
require_once 'Mobi/Mtld/DA/Api.php';
//Include the JSON file with the device data
$tree = Mobi_Mtld_DA_Api::getTreeFromFile('json/DeviceAtlas.json');
//Grab the User Agent string
$ua = $_SERVER['HTTP_USER_AGENT'];
?>

Great now we know the user agent that the user is using to view the website (well it may not be 100% accurate but better than nothing). So now you want to query the JSON file and pick out the relevant phone specifications you need. I’m just looking for the width of the device, so I included this in the head tag:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
    try {
        //Query the JSON file ($tree) with the User Agent string and look for the display width
        $displayWidth = Mobi_Mtld_DA_Api::getPropertyAsInteger($tree, $ua, "displayWidth");
    } catch (Mobi_Mtld_Da_Exception_InvalidPropertyException $e) {
        $displayWidth = 240; //Default to 240 if unknown
    }
   
    //Add stylesheet tweaks depending display width
    if($displayWidth == 480):
?>
    <link href="<?php bloginfo('stylesheet_directory'); ?>/480.css" rel="stylesheet" type="text/css">
<?php elseif($displayWidth == 320): ?>
    <link href="<?php bloginfo('stylesheet_directory'); ?>/320.css" rel="stylesheet" type="text/css">
<?php elseif($displayWidth == 240): ?>
    <link href="<?php bloginfo('stylesheet_directory'); ?>/240.css" rel="stylesheet" type="text/css">
<?php elseif($displayWidth == 176): ?>
    <link href="<?php bloginfo('stylesheet_directory'); ?>/176.css" rel="stylesheet" type="text/css">
<?php endif; ?>

All this code does is find the display width of the phone viewing the website and add a CSS file with relevant site tweaks, allowing you to optimise for that screen size. If the device isn’t found I’ve defaulted to a screen size in the middle of the screen sizes.

Looking through the API docs there are plenty of ways to distinguish between your users, using the following code will allow you to target specific phone brands:

1
2
3
4
<?php
//Output example $make = 'Nokia'
$make = Mobi_Mtld_DA_Api::getProperty($tree, $ua, 'vendor');
?>

So now you can target only Nokia users. Or instead of loading a different CSS file you could include a different sized image for different screen widths; there are tonnes of options available.

I must admit I really dislike having to ‘sniff’ for the user agent string and having a different CSS file / image per device width, it reminds me of the Netscape / IE browser war days, oh how much fun that was! I guess it’s a necessary evil.

A word or warning when it comes to DeviceAtlas, there seems to be distinct lack of support available. I wrote a couple of emails asking questions and got no reply, and lots of questions on the forum are left unanswered. So if you get stuck you may need to figure it out for yourself I’m afraid.

All in all I’m pleased with the results of my first adventure into the world of mobile web development. I still have lots to learn so if you have any tips and tricks please let me know!

Headspace2 JavaScript error

Update: An update of Headspace2 has just been released that seems to solve this issue as well as a few others.

After updating to WordPress 3.0 (yay!) I decided to check the plug-ins that I’ve written to see if they still worked in version 3.0; to my dismay Post Thesaurus had stopped working… nooooo! Not good! A quick scan using Firebug revealed the issue: the Headspace2 plug-in.

Headspace2 is a superb plug-in that allows you to tweak the SEO potential of your site. There are tonnes of options available; All In One SEO is easier to use, but I prefer the flexibility of Headspace2. The problem was occurring in the headspace-tags.js file:

1
2
3
$(get_tag_element()).val() is undefined
/wp-content/plugins/headspace2/js/headspace-tags.js?ver=3.6.32
Line 76

This error was stopping the rest of the JavaScript on a post page from firing (hence breaking Post Thesaurus). Looking at line 76 of headspace-tags.js you will see:

1
2
3
4
5
// Highlights headspace tags using the WordPress tag field as source
function highlight_tags () {
    var words = $(get_tag_element()).val().toLowerCase().split(',');
    //...
}

The code seems to be falling over when there are no tags, so I just added a ternary operator which checks the array length first.

1
2
3
var words;
var wordArray = $(get_tag_element());
(wordArray.length) ? words = $(get_tag_element()).val().toLowerCase().split(',') : words = [];

If there are no tags create an empty array, else run the usual code. Adding this code fixed the issue and Post Thesaurus works again. Phew! Panic over. I’m sure this error will be picked up by the developer straight away and fixed in the next update.

Snipplr under new management!

A few months ago I wrote a blog post regarding Snipplr, and how it was annoying it’s user base. By the look of it other people noticed the severe lack of development and abundance of spam and the site has been sold to envato.com (which I must say I love the site design).

With Envato behind Snipplr hopefully it will go from strength to strength. They already have a huge number of popular sites behind them including Nettuts and FreelanceSwitch which I read regularly.

Snipplr under new management

Under new management, huzzah! There have been improvements already! (no ads!)

There’s already been activity on the Snipplr twitter account asking for feedback, so here are a few of my requests:

  • Remove spam snippets & comments.
  • Better sign-up process to stop spam.
  • Fix the export function in the user preferences.
  • Better syntax highlighting (I hate having to click plain text before copy / paste).
  • Fix the blog links from the homepage, they have never worked for me.
  • Ability to remove comment spam from your own snippets.
  • Better design… the original orange was better than the current version.
  • Fix the gigs functionality, or at least explain how it works. I’ve never had much luck.
  • Use OpenID, I hate remembering all those passwords.
  • Ability for the API to output snippets as JSON-P.

Those are all I can think of at the moment but I’m sure there are others. Really looking forward to seeing how Snipplr evolves in the coming weeks and months!

High Resolution Icons for Google Chrome

I’ve been using Google Chrome as my default browser for quite a few months, I still use Firefox for Web Development but for general browsing you really can’t beat the speed of Chrome. One of my favourite Chrome features is the ‘Create application shortcuts…’ function. Creating an application shortcut essentially adds an icon to your desktop, Chrome will then run the web application like it is a free-standing desktop application (you still need to be connected to the internet unless it uses some form of offline storage).

If you are a Gmail user I highly recommend creating an application shortcut to see this function in action. One thing you will notice when you create the shortcut with Gmail is it uses a high resolution icon. If you create a shortcut using a standard website, by default the favicon.ico is used. As the favicon is limited to 16 by 16 resolution it will look very ugly blown up on your desktop.

Various application shortcuts I've created

You can really see the difference between the Gmail icon (left) and the standard favicons.

The image above really illustrates the difference between a 16 x 16 icon and a high resolution version. Now of course you could just change the icon in the Windows properties…. but that’s boring. Why not offer your users a high resolution image along with the standard favicon? It really is very simple:

1
2
<link rel="icon" href="/icon_32x32.png" sizes="32x32" />
<link rel="icon" href="/icon_48x48.png" sizes="48x48" />

Simply place this code in your head tag of your web application and link to the corresponding icons. Now when your user creates an application shortcut they will have a nice high resolution icon on their desktop.

Hi resolution Chrome icon

You can really see the difference when you add a high resolution icon

I’ve added a high resolution icon for my blog administration, now if only F1 live timings would do the same. For those of you who want to add a high resolution icon to your WordPress blog add the following code to your functions.php:

1
2
3
4
5
6
function wp_hi_res_admin_icons() {
    echo '<link rel="icon" href="/wp-content/themes/' . basename(dirname(__FILE__)) . '/images/icon_name_32.png" sizes="32x32" />'."\n";
    echo '<link rel="icon" href="/wp-content/themes/' . basename(dirname(__FILE__)) . '/images/icon_name_48.png" sizes="48x48" />'."\n";
}
add_action('login_head', 'wp_hi_res_admin_icons');
add_action('admin_head', 'wp_hi_res_admin_icons');

This will add the icon code to your administrator login panel and dashboard; or paste the raw HTML into your header.php so all users can see the icons.

Converting a WordPress post to a custom post type

Update: There is now a plug-in that does this for you called Post Type Switcher so you don’t have to get your hands dirty with the SQL (thanks Bruno!). Another plug-in called Convert Post Types is also available that does the job for you, Thanks to Steve for that one.

With the release of WordPress 3.0, developers now have the ability to create custom post types by adding a few lines of code to a themes functions.php. The feature is a huge step forwards for WordPress as it moves closer to being a viable CMS solution (without all the hacks). There have been a number of projects I’ve worked on that have required a custom post type; rather than relying on the client selecting the correct category under ‘Add new post’, which tends to always leads to issues.

I’m in the process of converting nooshu.com to use custom post types and taxonomies, the main area in particular is my portfolio section. At the moment the portfolio posts are just standard posts which have a category of ‘portfolio’ attached to them. It works, but I don’t get that warm fuzzy feeling, and it feels like a bit of a hack. So time to start using a custom post type of ‘portfolio’ (yay!).

Unfortunately at the moment there doesn’t seem to be a quick way of converting a published standard post into a shiny new custom post type, at least not from the administration area. After a little investigation work using phpmyadmin and the nooshu WordPress database, I discovered it’s actually quite easy. Be warned though, it’s easy to break your blog by editing the database directly, so make sure you back everything up. I take no responsibility for what happens if you break something!

To convert a post into a custom post type; in phpmyadmin look for the wp_posts table. Inside it do a search, where the ‘post_type’ value equals ‘post’. This will give you a list of all your posts (otherwise you will also have all the revisions and attachments listed). From the list you should be able to pick out the posts you want converting to your new post type, edit one of these posts and change ‘post_type’ from ‘post’ to your new custom post. In my case this would be ‘portfolio’:

phpmyadmin admin panel for a WordPress post

Change 'post_type' from 'post' to your custom post type.

Click save and go back to the previous page. Done! You should now see the post appear under your new custom post type in the WordPress admin panel. If you have any issues just change ‘post_type’ back to ‘post’ and it will reappear under the standard posts. No information is lost when changing the post type.

It’s not an ideal solution, hopefully it will be possible to do it from the administration panel in the future; but it does save having to re-enter all the posts under the custom post type for the moment.

Currently on page 3 of 1412345Last »