Modify wp_query for a specific category in category.php

Order by meta field in category.php

Aprile 8, 2016

Suppose you have a category called “events“, with a custom field with the date of the event, which is different from the post date. If you want to order the loop based on that field, only for that “events” category, you can do as follow.
Place it in category.php, at the beginning (or before the loop):

global $wp_query;
if($wp_query->query_vars['category_name']=='events') {
	$args = array_merge( $wp_query->query_vars, array(
		'orderby' => 'meta_value_num',
		'order'=>"DESC",
		'meta_query' => array(array(
			'key' => '_event_date',
			'value' => 0,
			'compare' => '>',
		))
	));
	query_posts($args);
}

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.