One of my friends asked me how to make WordPress query by custom fields. Let’s say he has a date custom fields in event post type and want to filter posts based on the date.
By default, WordPress has this capability. That’s why I loved WordPress
And of course, WordPress codex done the job very well.
| Post type | event |
| Custom field name | date |
| Custom field value | August 20, 2014 |
Build query parameter
$args = array(
'post_type' => 'event', /* If you leave it empty it would be 'post' by default */
'meta_query' => array(
array(
'key' => 'date', /* Custom field name */
'value' => 'August 20, 2014', /* Custom field value */
),
),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
echo get_the_title().'<br />';
endwhile;
endif;
That’s it. For more complex custom fields parameter, please refers to: http://codex.wordpress.org/Function_Reference/WP_Query#Custom_Field_Parameters