Skip to content

Instantly share code, notes, and snippets.

@billerickson
Last active December 13, 2019 18:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/494ea80eb8d5c427f45a to your computer and use it in GitHub Desktop.
Save billerickson/494ea80eb8d5c427f45a to your computer and use it in GitHub Desktop.
<?php
/**
* Order results by multiple meta keys
* @author Bill Erickson
* @link http://www.billerickson.net/code/order-results-multiple-meta_keys/
*/
/**
* Listing Query
*
* @param object $query, WordPress Query
* @return null
*
* @author Bill Erickson
*/
function be_listing_query( $query ) {
if( $query->is_main_query() && !is_admin() && ( is_post_type_archive( 'listings' ) || is_tax( array( 'listing-type', 'listing-location', 'listing-price' ) ) ) ) {
$sort = isset( $_GET['listing-sort'] ) ? esc_attr( $_GET['listing-sort'] ) : 'recent';
// Sort by Featured, then Most Recent
if( 'recent' == $sort ) {
$query->set( 'orderby', array( 'meta_value_num' => 'DESC', 'date' => 'DESC' ) );
$query->set( 'meta_key', 'be_listing_featured' );
}
// Sort by Featured, then Price (orderby filter toggles low/high)
if( in_array( $sort, array( 'price_low', 'price_high' ) ) ) {
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );
$query->set( 'meta_key', 'be_listing_featured' );
$query->set( 'meta_query', array(
'relation' => 'AND',
array( 'key' => 'be_listing_featured', 'compare' => 'EXISTS' ),
array( 'key' => 'be_listing_asking_price', 'compare' => 'EXISTS' )
)
);
}
}
}
add_action( 'pre_get_posts', 'be_listing_query' );
/**
* Listing Orderby
*
* @param string $orderby, SQL orderby parameter
* @return string $orderby
*
* @author Bill Erickson
*/
function be_listing_orderby( $orderby ) {
if( is_post_type_archive( 'listings' ) || is_tax( array( 'listing-type', 'listing-location', 'listing-price' ) ) ) {
$sort = isset( $_GET['listing-sort'] ) ? esc_attr( $_GET['listing-sort'] ) : false;
if( 'price_low' == $sort )
$orderby = 'mt1.meta_value+0 DESC, mt2.meta_value+0 ASC';
if( 'price_high' == $sort )
$orderby = 'mt1.meta_value+0 DESC, mt2.meta_value+0 DESC';
}
return $orderby;
}
add_filter( 'posts_orderby', 'be_listing_orderby' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment