Sorting wordpress posts by several numeric custom fields

Sorting by several custom fields (meta values) in WordPress seems like it should be easy. It is, but this is one of those things that are a little bit tricky to figure out how to do without having to write custom sql queries. I thought I would post the best solution I’ve found so far here in case it helps someone else in the future. Thanks to Rico at smartcode for the clearest explanation of the basics. This is more or less a replication of his post, with some minor edits and additions.

First, make sure you have the meta keys you want to sort by available in your arguments.

$args = array(
	'post_type'		=> 'your_post_type', 
	'meta_key'		=> 'your_first_metakey',
	'meta_query'	=> array(
		'key' => 'your_first_metakey'
		'key' => 'your_second_metakey',

Next, we need a filter function for the query. This modifies your query to sort by the first and second meta keys values. mt1 is a synonym for “meta key 1” and mt2 refers to “meta key 2”. As you see, this function is generic and you could use it in several queries where you want to sort by any two meta keys that you have specified in your arguments.

Now there is a funny little +0 at the end of the second meta key reference. What it does is specify that we want to make a numeric comparison. In a simple meta query you would instead replace “meta_value” with “meta_value_num” but that doesn’t work in this filter. An alternative to the +0 trick is to cast your data as decimal. You would then replace mt2.meta_value+0 with cast(mt2.meta_value as decimal).

function customorderby($orderby) {
	return 'mt1.meta_value DESC, mt2.meta_value+0 DESC';

Now apply your filter. Add it before your query and remove it afterwards to make sure it doesn’t affect subsequent queries.

$query = new WP_Query( $args );

When you start making more complex queries like this in WordPress you will probably notice some decrease in performance. My preferred way of dealing with that is to cache the results of complex queries with WordPress transients. If you haven’t worked with transients yet, I highly recommend checking them out when you have time.

Happy coding!

Responsive YouTube embedding for WordPress themes

The default code for embedding YouTube videos is an iframe with a set width and height. Iframes are not responsive and of course we want all content on our websites to be responsive. I found a neat solution to this at avexdesigns . However, this solution requires that you wrap the iframe in a container div. The whole point of using WordPress is to make life easy for our clients. We don’t want them to have to mess around with css and html. An easy fix for this is to dynamically wrap all iframe objects using jQuery.

Add the css from avexdesigns to your theme stylesheet. Then add simply add this little javascript to your theme

'); });

Assuming your theme is loading jQuery properly, any iframe code your customer adds to their site via WordPress admin will now be responsive automagically.

Using two or more domains on the same WordPress (multisite) installation might be easier than you think

Update 2021 – WordPress mulitisite now has support for multiple domain names out of the box. No extra plugins needed. Just point a domain to the document root of your multisite WordPress-installation, create a new site in the network and change it’s url to your new domain.

A lot of tutorials online make it seem rather difficult to use different domains for different blogs in your WordPress multisite installation. Depending on your server configuration I’m sure there are potential issues but it can be really simple.

1. You need to have 2 or more domains pointed to the same location and this location must be a root folder installation of WordPress multisite.
2. Download and install WordPress MU Domain Mapping plugin. Follow the installation instructions on the plugin page.
3. In the WordPress administration for the blog you want to set a domain for go to Tools/Domain Mapping. Add your (new) domain name and select “Primary domain for this blog”. Save.
4. You’re done!

If you have any problems during the installation it might be because of how your host handles domains. Remember that all domains must point to the same root folder install of WordPress. If you get problems you can always ask at the support forum for WordPress MU Domain Mapping.

Which CMS is your favorite artist using?

Because I am a coder one of the first things I do when I visit a website is to right click and view source. There is a lot of interesting information in there, if you are a code geek. You can see whether the site is running Microsoft or open source software. You can see how much of the site has been coded from scratch. You can see what plugins they are using and how “fresh” the code is. You can also often see what CMS software they are using. Today I was browsing famous artists websites to look at their design and code. This is what I found

Michael Jackson, Bruno Mars, Robbie Williams, Pink and Michael Bublé are all using Drupal. Rhianna, Katy Perry and Linkin Park have WordPress. Linkin Park also use Ning for their community features. I haven’t really heard a lot about Ning lately so that was somewhat surprising. Lady Gaga and Eminem are using a CMS I didn’t even know existed until today. It’s called Microgroove and it’s apparently a CMS built specifically for music/musical artist websites.

The website I found most interesting, code-wise, is Coldplay‘s which seems to have been coded from scratch. It’s not often you see that these days! Nice work Slender Fungus. 🙂

A little php to format numerical value as Swedish currency

So, you have a number which represents a price but you want it to be formatted as Swedish currency. There are different ways of doing this but not all of them are cross platform compatible. For example, php’s “money_format” doesn’t work on windows. I came up with this little piece of code that will do the trick.

This will insert a space every third character from the end of a string. So, 1000000 will be 1 000 000.

function makeCurrency($price) {
	$price_array = str_split(strrev($price), 3);
	$price_nice = strrev(implode(" ", $price_array));
	return $price_nice;

Extending and customizing Prism syntax highlighter

I have finally found the syntax highlighter I was looking for. Prism is a light weight Javascript + css syntax highlighter written by Lea Verou. A syntax highlighter is a program that will help you make any bits of code you want to publish on your website look prettier.

Other than it really being very light weight and easy to install, another thing I love about Prism is that the code is easy to extend or modify according to your needs. Here is an example of how to make Prism highlight an additional element not included in the default download.

Tokens that are used to create css classes are constructed in prism.js. Now if we want to add highlighting of php style variables when applying the “javascript” language, all we have to do is add a line in the javascript language definitions in prism.js. The line we are adding is 'phpvars': /$.*/ and what it does is construct a new token css called “phpvars” which matches any word that starts with dollar sign.

 Prism.languages.javascript = Prism.languages.extend('clike', { 'keyword': /b(var|let|if|else|while|do|for|return|in|instanceof|function|new|with|typeof|try|catch|finally|null|break|continue)b/g, 'number': /b(-?(0x)?d*.?[da-f]+|NaN|-?Infinity)b/g, 'phpvars': /$.*/, }); 

Then we have to style our new class! In prism.css add the following class

 .token.phpvars { color: blue; } 

That’s it! Now any php code we put within pre or code tags with the language “javascript” declared in the tags class will highlight php style variables. So this

 if (false !== strpos($allowedTags, 'comment')) { $escapedContent = preg_replace_callback('|<!--.*?-->|is', 'tguy_cmu_unescape_tag', $escapedContent); } 

Will now look like this

 if (false !== strpos($allowedTags, 'comment')) { $escapedContent = preg_replace_callback('|<!--.*?-->|is', 'tguy_cmu_unescape_tag', $escapedContent); } 

The only tricky part of this is that you need to have some clue about how regular expressions work to be able to select exactly the piece of code that you want to highlight. There are plenty of resources and tutorials online to help you along the way and be sure to check out which has answers to many common programmer dilemmas.

If you are happy with the default classes that Prism constructs, you can always play around with the css file, modify the colors and add other styling as you wish.

Bitnami wordpress stack running slow on Win 7?

I have been running the bitnami WordPress stack to run WordPress locally for quite some time. I absolutely love it and strongly recommend it for anyone obsessed with WordPress. Download it and a few clicks and you have a stable local development/testing environment up and running. However, on my last installation it was really slow. Took me a while to figure out but it seems Windows 7 has some problems resolving “localhost”. If you have the same issue, check wp-config.php to make sure it’s pointing to instead of localhost.