Getting the category ID in WordPress

February 4th, 2010

There is quite a bit of documentation in the WordPress site about categories, specifically how to retrieve data about them. Unfortunately all the available methods seem to focus on getting category data from a post, but it’s nearly impossible to figure out the category you are looking at when viewing the category page itself (i.e. the special “archive page” that lists all posts in a category).

The function is_category() falls short, since it only indicates whether or not the current page is a category page, but not which one. And get_cat_id(), get_category(), get_the_category(), and the half-dozen other “obviously”-named functions either require that you already know something about the category or provide information about a post.

So, the solution?

if (is_category()) {
   $categoryId = $GLOBALS["cat"];
}

Yes, it’s a global variable…

Making sprites

December 23rd, 2009

So you have a website that uses dozens of little images to make the interface more attractive. Maybe there’s a toolbar or menu, where each item or button has its own icon. It looks great, but it’s a pain to load – each image is a small file and the browser frantically struggles to manage the 20 or 30 requests for all the graphical nicety. The interface feels sluggish. Users get bored and leave. Civilisational collapse soon ensues.

Fortunately, you know how to fix the problem with the use of the great technique of CSS Sprites. If you don’t, you should. Click the link and learn about it; I will assume that you know what CSS sprites are from here on… Yes, CSS sprites are great, but they are a pain to create manually. Not only you need to stitch the images together but also there will be lots of CSS rules to position the background image correctly. Automation comes to the rescue in the form of the montage command (part of the fantastic ImageMagick collection of image-manipulation software goodness) and some quick script hacking…

Creating the sprite

This little tip will create a sprite off a directory of image files with identical size (in this case, 16×16 icons), each one named something sensible. The objective is to get one image file and a bunch of CSS rules built automatically. First, ensure that you have ImageMagick. In Ubuntu this command will do the trick:

sudo apt-get install imagemagick

There are also downloadable distributions for Windows and Mac. Once you’re ready, open a command prompt and go to the folder where your images live, and run this command:

montage *.png -alpha on -background "#ffffff00" -tile x1 -geometry 16x16 ../sprites.png

This will create a file, sprites.png, in the parent folder (in Windows, make sure that you type “..\sprites.png” as the last parameter – notice the backslash), with all the images tiled side-by-side. If you require the images to be tiled top-to-bottom substitute -tile x1 with -tile 1x. And if your images are a different size than 16×16, specify that in the -geometry parameter. And if your source images are not PNGs, replace “*.png” as appropriate. I recommend that you open the sprites.png file in your editor of choice and perform any conversions or optimisations as you see fit. Don’t forget to apply OptiPNG if you use PNG as your final format (why wouldn’t you?) to get a really small final file size. Your sprites file will look a bit like this (icons off the excellent Silk Icons set):

Example of icons in sprite file

That takes care of the sprite image. Now for the CSS rules.

Auto-generating CSS rules

We’ll be defining a couple of base rules that apply to all elements (note the references to 16px, the size of the icons; adjust as necessary):

.i16:before, .i16 span {
    content: "";
    background-image: url("sprites.png");
    background-repeat: no-repeat;
    padding: 0 0 0 16px;
    margin: 0 0.25em 0 0;
    *zoom: 1;  /* For IE 6 and 7 */
}

.i16block {
    display: block;
    margin: 0 0 0 16px;
    padding: 0 0 0 0.25em;
    position: relative;
    *zoom: 1;  /* For IE 6 and 7 */
}

.i16block span {
    background-image: url("sprites.png");
    background-repeat: no-repeat;
    height: 16px;
    left: -16px;
    min-height: 1em;
    position: absolute;
    top: 0.115em;
    width: 16px;
}

And one more rule per image, which provides the correct background position. The objective is to be able to use classes like this (in this case, to obtain the PDF icon):

<a class="i16 i16pdf" href="example.pdf">PDF link</a>

Or, for links that might span multiple lines and require nice text alignment (or for IE6 support) we need an extra element:

<a class="i16block i16pdf" href="example.pdf"><span></span>PDF link</a>

First, we need to get a list of files in the directory. Each file will produce a rule, and it is important that the contents of the directory haven’t changed since the sprite was created (this is why we placed the sprite in the parent directory). So, drop to the command line and, in Linux, run this:

ls -1 *.png > filelist.txt

Or, in Windows:

dir /b *.png > filelist.txt

Now we only need a quick script to output a bunch of CSS rules. This can be done with your favourite programming language, but here is an example in Python:

rules = ""
f = open('filelist.txt', 'r')
x = 0
for name in f:
    rules = rules + ".i16Mime" + name[0].capitalize() + name[1:] + ":before"
    rules = rules + ", .i16Mime" +  name[0].capitalize() + name[1:]"
    rules = rules + " span {\n    background-position: -" + str(x) + "px 50%;\n}\n\n"
    x = x + 16
f.close()
f = open('rules.css', 'w')
f.write(rules)
f.close()

The above code can be saved as a Python script file (say, “myscript.py”) in the same directory as the images, and run from the command-line like so:

python myscript.py

This will generate a new CSS file, “rules.css”, with all the correct rules for all the icons. It should be pretty easy to rewrite the above in your language of choice (PHP, Ruby, Assembler…)   Simple apply to your links the appropriate “i16 i16type” class names and you should be good to go.

Too big to work?

November 29th, 2009

Without trying to dismiss the complexity of the problem, how hard can it be to implement an Europe-wide train booking system?

BBC: “Euro train booking system shelved

Is IT still such a headache that these systems are too hard/expensive to implement? I say make the routing, timetable, and booking information freely available and I’ll have a go at making it work…

Testing for outline CSS support with jQuery

November 27th, 2009

In the good spirit of testing capabilities rather than browser versions, I needed a way to find out whether or not a browser supports setting the values of the “outline” property via CSS. IE6 and 7 don’t support it, everything else seems to. So I just quickly extended the jQuery.support functionality like so:

$.support.outlineCss = function() {
    var $el = $("<div></div>").css("outline", "1px solid black"),
        outlineStyle = $el.appendTo(document.body).css("outline-style");
    $el.remove();
    return outlineStyle == "solid";
}();

Simply test if $.support.outlineCss is true and you’re good to go…

Moving to WordPress

November 8th, 2009

I’ve been planing this for a while, but I’ve finally gone ahead and done it. I ditched my previous site, which was built as an amalgamation of Serendipity (S9Y) and Zend Framework (ZF) and moved to WordPress.

Why? Mostly because the previous setup still required quite a bit of work for me to be happy with it: it looked OK for a visitor, but integrating S9Y into an MVC framework like Zend was somewhat nightmarish, and the admin interface was quite cumbersome even for simple things like adding a post. So I’m setting up a vanilla WordPress installation (apologies about the design; I’m working on it!) which will hopefuly translate into more interesting content and less hassle for me!

I initially set up a ZF site to try and get some more experience with the framework itself, and I am very glad I did. It was a completely overkill application of the technology but I feel I can now use ZF for quite more complex applications: it is very capable and powerful while avoiding the typical “application server” setup that seems so common with larger frameworks. I especially liked the way you can cherry-pick which parts of the framework are of interest, including whether or not the whole MVC stack gets used. For simpler applications something like Cake PHP might still be a faster and simpler way to do things, and I’ll keep to plain-no-frills-PHP for really simple things like prototyping.

As for S9Y, it was a bit of a disappointment. I was looking for a blogging engine that could be plugged into my ZF setup, but since there seem to be none that are happy to do that kind of “blog backend” role only, I settled for something that seemed easy to hack into submission. S9Y does bring its own kitchen sink as well, but it seemed easy to hack. However, two things let it down: convoluted, poorly-documented code, and the templating system.

I won’t say much about the code quality, except that it was at first sight simple but in fact quite messy once you tried to wok out interactions between different parts. The lack of documentation was the really frustrating part, though. So far WordPress seems much better documented and understandable.

The templating system of S9Y is Smarty. There’s nothing wrong with Smarty itself; I guess my problem is with templating systems in general. I know these have their usefulness in some development environments, and of course it is essential to separate as much logic as possible from your markup. However, I don’t think templating systems are a great solution: many times the behaviour of a template is itself complex, and a custom-syntax, crippled language like Smarty is a hindrance.

So there you have the reasons for moving on. Both ZF and S9Y had its fun moments but that setup wasn’t really suitable for this tiny site. Getting rid of the not-invented-here syndrome is also a good thing. In the coming days/weeks I hope to put together a nicer design (I promise I’ll go easy on the orange…) and I now also have fewer excuses to create content more often. So overall I think this was the right decision!

Back to HTML?

June 4th, 2009

There have been a couple of controversial posts flying around lately… I thought I’d add my two cents…

Should we go back to HTML 4? The argument is that XHTML hasn’t really delivered on the promises of a semantic, extensible web, and probably won’t do so in the foreseeable future; instead HTML 5 is starting to look like the next holy grail (I have some views on HTML 5 in an earlier post). So let’s ditch XHTML and get ready for HTML 5 by jumping to the latest HTML version (that’s 4, if you’re still with me).

Hold on, what?

My new watch doesn’t tell me the time in five different timezones, so I’ll go back to using my old sundial because there’s a new type of sundial in the making that will! My mobile phone doesn’t have great coverage so I’ll use my old fixed phone instead! Ubuntu doesn’t support DRM’d desktop background images, but the next version of Windows will, so I’ll switch back to XP…! OK, OK, maybe I’m stretching comparisons somewhat, but the basic premise remains: why would you go back to something that has more disadvantages right now when the reason for doing so has nothing to do with it? There’s nothing to gain.

First off, HTML 5 will maintain XML compatibility in its XHTML 5 incarnation. The current spec doesn’t dwell much on it, because in terms of DOM there should be no difference between the two. The strict parsing and reconciliation rules guarantee that. If you use the XHTML version you get the additional XML validation — if you want it. But HTML 4? There are no such rules, it is easier to write non-conformant code that renders completely differently in different browsers. The syntax is lax, and therefore more prone to breaking. In short, rules in XHTML are much clearer. So, although HTML 5 will address a lot of the bad effects of malformed documents, XHTML (whichever version) helps to address the causes.

If the argument is that you want to line up your markup with the new HTML 5 tags like <nav>, why wouldn’t you do so with XHTML? Here’s the difference:

<!-- HTML 4 --> <div> <ul> <li>... <li>... </ul> </div> <!-- XHTML 1 --> <div> <ul> <li>...</li> <li>...</li> </ul> </div> <!-- (X)HTML 5 --> <nav> <ul> <li>...(</li>) <li>...(</li>) </ul> </nav>In case it wasn’t clear: I’m sticking with XHTML 1 for now, thank you very much. I shall jump to XHTML 5 when I feel it’s time; I like to close my tags.

I had something else to say about using px as font-size units, but I’ll save that for a later post… Don’t want to rant too much…

Google Wave

June 2nd, 2009

Every now and again you get to see something that makes you really proud of working in IT… Google Wave’s initial premise to “re-think email” instead makes people rethink the way they use their computers to communicate. It is great to be part of an industry that has such tremendous potential to be useful and dramatically change the way we work, play, and socialise.

So, OK, I’m not actually part of the Great Google Family who has built this thing, but I hope to have a chance to build on it soon… Hurray for open source!

For now I thoroughly suggest watching the full one-hour-twenty presentation. It’s worth it.

HTML 5

April 1st, 2009

Despite Adobe and Microsoft probably wishing otherwise, the vast majority of the web is still built using trusty ol’ HTML, with its now inseparable partners CSS and Javascript. The latest valid specification of HTML (4.01) will celebrate a decade of existence by the end of this year, so it seems appropriate that a shiny new version is in the works.

Since the web is the vehicle for the ongoing information revolution (which itself is transforming so many areas of the lives of billions of people all over the globe), it is important that the basic building block of the web – HTML – is up to the task: it must continue to support rapid, exciting, and unpredictable developments in the web. It’s a lot of responsibility. Enter HTML 5.

There is a lot on the current Working Draft, so instead of listing all new features and changes (plenty of other sites do that already) I thought I’d share my thoughts about some of the features instead.

Good stuff in the current Working Draft

The lexer and parsing rules. These are great, even if their true usefulness for “serious” web development might be somewhat limited. Now any syntax error on the HTML code will result in the same final DOM and hence the same base model for rendering the page – so HTML rendering will be consistent (or at least consistently broken) across browsers.

Focus on the DOM. This is closely related with the above point. HTML 5 defines both the syntax of the new language but also the structure of the DOM used internally by the browser (and the rules that DOM must follow). In theory, this should bring about much more cross-browser coherence.

New APIs (drag & drop, offline and storage support, canvas, media control). Each one of these is worthy of it’s own blog post, but here’s the shortest summary possible:

  • If you ever tried handling drag & drop on a browser you would probably have offered one of your own lungs to try and make the process easier. Even the existing Javascript library solutions suffer from quite bad performance for this most common of UI operations. Having in-browser support is a sure winner.
  • Offline state and storage support are essential for reliable web applications and can truly bring about the slow death of fat desktop environments (mmmn, I wonder when will Microsoft implement this in IE…)
  • Canvas and media control APIs are essentially the second step towards Flash/Silverlight without Flash/Silverlight: complex UI widgets built with Javascript. (The first step, by the way, was simple animations provided by JS libraries.)

Removal of presentational elements and attributes. Good riddance. This might actually focus some minds into separating their markup from presentation. Now, if only there was a way to get rid of tables-for-layout as a language feature…

Web sockets. Goodbye polling, hello highly-specialised, highly-efficient web applications. This will put current Comet techniques to shame.

Not quite-so-good stuff

Lots of new arbitrary elements and attributes. This is my pet peeve with HTML 5. What is a sensible new element today might be redundant tomorrow as the patterns of semantic organisation change. Furthermore, there are an incredibly large number of other potential elements that would make much more sense to specific areas of work but aren’t included. So we will get <head> and <article> and <aside> and <datagrid> and another thirty-something (at the last count) new elements and attributes. I believe this is the wrong solution, where we are forcing very specific meanings into the language that will be both useless in a large variety of cases and deprecated in the not-so-far future.

The main issue that developers seem to battle with is how to apply a specific semantic model to the language. By adding new elements with pre-determined semantic meanings we are perhaps solving some of the common problems but have not addressed the root causes of the problem: we need custom semantic models. I believe XML has solved this problem with DTDs and namespacing, but those solutions fail for the web due to complexity.

I am not offering a solution to the above problem, I am simply pointing out that the new tags are the quick solution, not the best one. Maybe we could use something akin to annotations in Java? Anyway, that’s a topic for a later blog post…

Editing API. It’s a good idea, but the current specification amounts to little more than a roughly outlined wishlist of a concept. This is not to bash (hard) work-in-progress, but I don’t think the HTML 5 language itself should be concerned with defining the behaviour of a GUI IDE for itself. This is a big project in its own right.

It’s too big. The current Working Draft looks too much like a huge wishlist, with many features being defined within the spec itself. Smaller specs should be split into their own documents and HTML 5 should simply specify its dependencies on those documents. This includes the rather verbose “common microsyntaxes”, several parsing rules (URLs, content-sniffing), canvas API, etc. Trimming things down should also simplify adoption and allow for a more solid spec. For instance, if a given dependency is not defined solidly enough it should be easier to depend on a simpler/earlier version, or even scrap the dependency altogether in favour of having a well-defined HTML 5 spec.

Web sockets. Yes, I listed this above in the “good stuff” section. It also has the potential to put too much power in the hands of web developers (not always famed with good application design). Seriously, though, the web has flourished on top of the HTTP protocol, and although this feature will probably be a good thing it must be treated cautiously due to introducing a different paradigm for data transmission over the web.

Why isn’t there more buzz?

There has been a fair amount of discussion regarding HTML 5, but given the fundamental aspect of what is being changed I guess I expected some more enthusiasm (or hype). Partially I believe this is not happening because of the scale of the project and the fact that it’s still a far-off prospect. “Cool” (OK, let’s call them “popular”) new web technologies seem to generate buzz and grow in adoption in a matter of a few months. They tend to be something that developers can simply pick up and use: microformats, embedded maps, web service APIs, Javascript libraries… HTML 5 is not something that you can use right now and reap any significant benefits from.

The other aspect is that the current HTML implementation is not such a big problem at the moment. Most of the quirks are well-honed, and solutions to problems have long been known and worked around. Most of the bigger problem faced by web developers are related to either CSS or Javascript. The truth is, the current flavour of HTML has withstood the last ten years well because it does it task remarkably well: it provides a stable infrastructure for defining the semantics of content, over which the presentational (CSS) and behaviour (Javascript) layers can work.

In any case, this is definitely a worthwhile project which will eventually offer some real benefits to the world of web development even if by itself it will probably not be the driving factor of a great information revolution – that has been with us for almost ten years now.

UK Government backs Open Source

February 26th, 2009

Now, here’s something you seldom see these days: good news from the UK Government.

Having grown accustomed to Government-backed IT projects like the national air-traffic control system or the positively mind-warpingly expensive NHS IT system, it’s good to see that maybe — just maybe — there is some hope for sanity in large-scale public IT projects, and not everyone has been dazzled by the marketing departments and flashy buzzwords of the big corporations.

For posterity, here’s the actual document (interestingly, it seems to be served from a Microsoft web server… Ahem.)

Layout Systems

February 19th, 2009

There’s a really interesting discussion going on at Eric Meyer’s blog regarding (the lack of) a decent layout system for the web. There’s also the usual troll-/flame-/bitch-fest brewing in the comments, but there are a few pearls in there that I think are worth extracting for some extra thought:

  • Nick Morgan suggests a grid concept to be used for layout by implementing relationships between element’s grid parameters
  • kylegl sums up the problem as the inability to define relationships between elements
  • AlastairC mentions that there is already behavioural layout implementations in JS
  • CSS Annoyed again brings up element relationships as the problem

I also learnt about the strange world of the W3C’s CSS Advanced Layout Module. I agree with Eric; it’s ASCII Art! I need to think a bit more about these things… I’m sure there is a solution, or at least something wise to be said.