Skip to content

Sort WP_Query By Engagement

ryanburnette edited this page Dec 2, 2012 · 1 revision

The first and most obvious function of the plugin is to maintain current_engagement and max_engagement values. The current engagement value is based upon factors which increase the number, then a rotation period decreases the number so it experiences a natural fall over time. The max engagement value tracks the highest point engagement ever reached.

One may want to sort posts based on these values. WordPress' built-in WP_Query class provides us with a way to do this. It also provides a way to sort by secondary parameters. In cases where many posts may have the same engagement value, this secondary parameter allows order to applied to those ranges. Developers should read WordPress' documentation on WP_Query for more information.

Here is an example of a custom WP_Query which is sorted first by the current_engagement value then by date.

$args = array(  
	'post_type' => 'my-custom-post-type',  
	'orderby' => 'meta_value_num date',
	'meta_key' => 'current_engagement',
	'order' => 'DESC'
);
$obe = new WP_Query($args);
while ( $obe->have_posts() ) {
	$obe->next_post();
	print_r($obe->post);
}
wp_reset_query();
Clone this wiki locally