How to query wordpress posts by custom meta

February 16, 2012    custom wordpress custom-meta custom-meta wordpress custom_meta wordpress Wordpress

Wordpress custom meta for posts and pages (including custom post types...obviously) can open the door to extending Wordpress in many great ways.

One such way is enabling custom input areas on the backpanel for specific post types and using them to store more specific information for each project you undertake.

For example say you've got a wordpress project which your client needs to be able to add and edit farm animals onto their site. Great! Custom post type time I here you say.

But wait...! You can use the title for the name of the animal and the main body to explain a bit about it, but what about storing the animals weight or how many you have of that animal on your farm. Simple answer, you can't, well least not in a nice way.

Enter custom meta.

I'm not going to get into how to add custom meta to a custom post type, or indeed any type of post on Wordpress, but I will show you how to use it in a WP_Query so you can query what you've created on the front end.

Now lets consider querying the top 5 weight heavy animals on the farm where farm animal type = nondairy.

    $loop = new WP_Query( 
    array( 
        'meta_query' => array(
	    array(
		'_myfarm_animal_type' => 'nondairy',
	    )
	),												
	'post_type' => 'services',
	'posts_per_page' => 5,
	'caller_get_posts' => 1,
	'orderby' => 'meta_value',	
	'meta_key' => '_myfarm_animal_weight',
    ) 
    );	

Wallah!

Great huh? Not quite farmville, but you get the gist.

I may extend this post further in the future so check back if it interest's you.


blog comments powered by Disqus