WordPress: Query Posts

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.

This entry was posted in Programming and tagged , , . Bookmark the permalink.

One Response to WordPress: Query Posts

  1. PD says:

    Thanks a lot for sharing this info. This information was indeed very helpful as I was trying to retrieve posts based on tag names (which have spaces) and could not find a way to this anywhere – Finally found your blog and it works perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>