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…

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.

Recommended

WP Gutenberg notes

Collection of notes and thoughts on Wordpress Gutenberg blocks development.

Gennaio 9, 2023

Test page for Bright Links plugin

To test the plugin hover your mouse to a link, or tap the link on mobile device.

Dicembre 4, 2022

Updating a metabox after Gutenberg updates

When press on "Update" refresh a custom metabox under gutenberg editor.

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

Febbraio 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…

Novembre 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

Novembre 7, 2019