How to adjust the default listing sort by price and rent
Using the WordPress pre_get_posts filter you can create a simple function to adjust the default sort of listings with the following function.
Add the following function to your theme functions file or custom plugin.
function my_epl_listing_default_sort( $query ) {
// Do nothing if in dashboard or not an archive page
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// Do nothing if Easy Property Listings is not active
if ( ! function_exists( 'epl_all_post_types' ) ) {
return;
}
// Do nothing if doing search
if ( epl_is_search() ) {
return;
}
// Do nothing if using sorting
if( isset ( $_GET['sortby'] ) ) {
return;
}
// Sort EPL listings by price on archive page
if ( is_post_type_archive( epl_all_post_types() == 'true' ) ) {
// If rental post type sort by property_rent meta key
if ( is_post_type_archive( 'rental' ) ) {
$query->set( 'meta_key', 'property_rent' );
} else {
// Default for other post types
$query->set( 'meta_key', 'property_price' );
}
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );
return;
}
}
add_action( 'pre_get_posts', 'my_epl_listing_default_sort' , 20 );