nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: Wordpress

Posts on anything related to the Wordpress blogging platform including themes, plug-ins and general tips.

Nooshu.com now with added HTML5 goodness

So I finally pulled my finger out and took the HTML5 plunge over the past day or so; the Nooshu WordPress theme now has a sprinkling of HTML5. Mmmm I have that warm fuzzy feeling of completeness! In all honesty it’s been an easy way to learn about the new HTML5 specifications (although they aren’t complete and won’t become a W3C recommendation until 2022… no that isn’t a typo!).

HTML5 has added a host of new tags which have much more semantic meaning. So instead of using ‘divs’ to section off areas of your page layout, you can now use:

1
2
3
4
5
6
<!-- Some of the new HTML5 Tags -->
<header></header>
<footer></footer>
<article></article>
<section></section>
<nav></nav>

It’s certainly a welcome addition to the modern web. My favourite part of HTML5 has to be the doctype (other than the canvas element):

1
2
3
4
5
<!-- No more -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<!-- Much better! -->
<!DOCTYPE html>

Look how simple it is! No more copy / paste from a previous project for this doctype.

My main concern when converting the theme to HTML5 was how it would work in IE; as IE8 supports parts of HTML5 but IE6 and IE7 not at all. When IE comes across a tag it doesn’t recognise it just ignores it. Since the tags aren’t recognised you won’t be able to style your lovely new HTML5 template in IE6 & IE7. Lucky you can patch this missing functionality using JavaScript. Remy Sharp has created a script called html5shim, that adds the missing tags to IE. Just add the following code to your header and you will now be able to style your HTML5 tags:

1
2
3
<!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

The script must be in the header and must fire before the DOM is created. The script simply creates all the new HTML5 elements using the document method ‘createElement’, you don’t even need to attach the created elements to the DOM! Now IE will recognise the tags and you can get on with your page styling. Yay!

Those who use WordPress 3.0 may have noticed that the default Kubric theme is no more and it’s been replaced with a new theme called twenty ten. The theme uses the HTML5 doctype but it doesn’t use any of the new tags. I guess because of the IE issues. Maybe this will be changed in future releases.

The Nooshu theme is still a work in progress, and I’ll modify areas as I learn more about the new HTML5 features. Here are a selection of links that I found incredibly useful while working on the theme:

  • Dive into HTML5: Read through this article and you will be well on your way to learning HTML5. It delves into the history of HTML and progresses forward right up to implementing the new specifications.
  • HTML5 Doctor: Looking for HTML5 related news or need some clarification of a new tag? Look no further than HTML5 Doctor. Lots of articles available for you to read and there’s even the option to ask a question if you don’t find the answers you are looking for.
  • HTML 5 Outliner: So you’ve created your shiny new HTML5 template; why not check it with the outliner to see if it makes sense to a user / search engine.
  • W3C Markup Validator: It’s been a while since I’ve used a validator since I have one built into Firefox, but the W3C validator was very handy for pointing out attributes and tags that are no longer supported in the specifications. It also gives you a quick benchmark to aim at.

If you have any other useful HTML5 tips and links let me know below.

WordPress plug-in: Snipplr Snippets

Recently I blogged about the fact that Snipplr was under new management!, and what great news that is. You can see the changes being made already, fingers crossed they manage to nail the spam issue.

Back when Snipplr was young, Tyler Hall wrote a WordPress plug-in for Snipplr that allowed you to embed your snippets directly into your posts. What a great idea; unfortunately it hasn’t been updated since 2006 and much has changed in the world of WordPress. Enabling the plug-in in it’s current state is a little flakey; so I’ve decided to update it for WordPress 3.0+.

The plug-in is called ‘Snipplr Snippets’ and is available to download from the WordPress plug-in repository. I’ve used many of the functions that were in the old plug-in so it isn’t a complete rewrite but much of the structure has changed (big thank you to Marcin Dominas helped with a couple of issues i was having at first).

View of the snippler snippets side bar.

Snipplr Snippets sidebar widget in action.

The administrator area has been updated and there are a couple of new features available which hopefully are self explanatory. I’ve also updated to the latest version of GeSHi for the syntax highlighting, if you don’t like the look a feel of the outputted code simply disable the plug-in CSS in the site header (admin panel), copy to your style.css and modify as needed. For the plug-in to work you will need a Snipplr account and an API key (available from the settings page).

Once you’ve installed the plug-in and enabled it, it’s dead simple to include a snippet into your blog post like so:

1
2
//Remove the spaces inside the brackets.
[ snippet id=## ]

Where the ## is the ID of the snippet you wish to include in the post (you can get this from the snippet URL). The code below is pulling in a snippet directly from Snipplr using the plug-in:

  1. (function($){
  2.         $(window).load(function(){
  3.                 //Wait for the page to load, the cache the files you want
  4.                 $.ajax({url:‘javascript.js’, dataType:‘text’});
  5.                 $.ajax({url:‘image.jpg’, dataType:‘text’});
  6.                 $.ajax({url:‘flash.swf’, dataType:‘text’});
  7.                 $.ajax({url:‘style.css’, dataType:‘text’});
  8.         });
  9. })(jQuery);

I’ve tested the plug-in and it seems to work fine, there was a warning from the CodeColorer plug-in because it also uses GeSHi for syntax highlighting but I haven’t noticed anything break because of it. If it does please let me know and I’ll fix it. If you have any suggestions / bugs leave a comment and I’ll see what look into implementing / fixing them. Download here.

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.

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 1 of 41234