wordpress-logo-(1).gifOne of my favourite features of WordPress is that it lets you create custom fields for storing information relating to specific posts or pages. This is really useful when using WordPress as your CMS, because it lets you associate specific pieces of information with certain elements of your site, which you can then use when developing your theme template.

One issue that I came across whilst recently working on a WordPress site was that I needed to check the database for the existence of a value for a page’s custom field and assign it a default value if it didn’t exist. The initial code for this worked out to be quite verbose.

Now being the OCD perfectionist that I am, I wanted to do this in as little code as possible, the following is what I came up with. This code snippet will essentially grab the value of the custom field named ‘tb_width’ if it exists and assign it a value of 120 if it doesn’t.

$tb_width = ($tb_width = get_post_meta($post->ID, 'tb_width', true)) ? $tb_width : 120;


Now I realise that it would be better for performance purposes if we did this the long way (probably), but I like that this will only ever need occupy one line of code in your template and sometimes readability and neatness is important.

Obviously use this at your own risk and I welcome any comments/criticisms that aren’t pedalling pharmaceuticals.

You may also like

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.