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

Limit the number of categories for posts in WordPress

CHOOSE ONLY ONE CATEGORY WORDPRESS If you need to limit the number of categories used by the authors of your…

September 14, 2015

How to remove custom fields from WordPress

Ok. You’ve added custom fields in wordpress, but how can you remove them? How to delete custom fields wordpress Two…

September 29, 2013

A new avatar generator for WordPress with get_avatar and Flathash

Brand new avatars for WordPress Gravatar service

April 7, 2017

3 ways to add author’s image in WordPress

Add author's image in WordPress without a plugin

April 5, 2017

Stop sending email to new user in WordPress admin registration

Prevent WordPress to send notification emails when you manually create new users

March 9, 2017

Add filter on wp_title not working with Yoast SEO plugin

For SEO purposes, in a specific template that has a list of items with pagination, I need to have different…

February 22, 2017