Wordpress

WordPress: How to Query Posts by Custom Fields?

Oleh takien

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

Tulisan ini sudah berumur: 12 tahun 17 hari. Informasi di dalamnya mungkin sudah tidak relevan, tapi nilai historisnya sangat berharga, terutama bagi saya sebagai penulisnya.