Modify wp_query for a specific category in category.php

Suppose you have a category called “events“, with a custom field with the date of the event, which is different…

April 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

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

February 8, 2020

Two post types share the same taxonomy in WordPress

Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different…

November 14, 2019

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

November 7, 2019

WordPress Fatal error: Unknown: Cannot use output buffering in output buffering display handlers in Unknown on line 0

How I've beat the php mysterious fatal error unknown in Wordpress caused by caching plugin WP Fastest Cache

WordPress Gutenberg doesn’t parse Istagram oembed url

Sometimes Instagram embed doesn't work, why?

November 4, 2019

Stop sending email to new user in WordPress admin registration

A code snippet to prevent WordPress to send notification emails when you manually create new users. It uses a pluggable function.

November 1, 2019