Posts Tagged ‘wordpress’

WordPress: Query Posts

Friday, February 6th, 2009

When you are interacting with WordPress’s Query Posts function the codex page gives great examples.

However, the one glaring omission is documentation on how to handle variables with spaces. For example you might want to query for posts with the tag “Converse”, this is easily achievable with:


# the query terms are not case sensitive, so converse==ConVERsE==Converse

query_posts('showposts=1&tag=converse');

But what if you wanted to query for a tag that contained spaces in it, like “Onitsuka Tiger”? Unfortunately none of the examples on the WordPress page currently provide an answer and giving the query_posts function spaces doesn’t result in anything. And while you might assume urlencode or rawurlencode might be the answer – they’re not.

The answer is that the spaces must be replaced with hyphens:


$manufacturer_tag=str_replace(' ', '-', $manufacturer_name);

query_posts('showposts=1&tag=' . $manufacturer_tag);

Apart from that omission the WordPress codex is still undeniably one of the greatest examples of an OSource API.