Created
August 29, 2025 06:37
-
-
Save propertyhive/4f578b1e11141dab92b40087e82e5e2a to your computer and use it in GitHub Desktop.
Order digital displays by availability
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| add_action( 'pre_get_posts', 'custom_order_dd_properties_by_availability', 10, 2 ); | |
| function custom_order_dd_properties_by_availability($query) | |
| { | |
| if ( is_admin() ) | |
| { | |
| return; | |
| } | |
| $post_type = $query->get('post_type'); | |
| if ( !is_array($post_type) ) { $post_type = array($post_type); } | |
| if ( !in_array('property', $post_type) ) | |
| { | |
| return; | |
| } | |
| $availability_order = get_option('propertyhive_taxonomy_terms_order_availability', array()); | |
| if ( empty($availability_order) ) | |
| { | |
| return; | |
| } | |
| if ( | |
| strpos($_SERVER['REQUEST_URI'], 'digital-display/') !== FALSE | |
| ) | |
| { | |
| // Sanitize and prepare the order | |
| $availability_order = explode("|", $availability_order); | |
| $availability_order = array_map('intval', $availability_order); | |
| // Modify the main query to join with term relationships and term taxonomy tables using custom aliases | |
| add_filter('posts_join', function ($join, $query) | |
| { | |
| global $wpdb; | |
| $post_type = $query->get('post_type'); | |
| if ( !is_array($post_type) ) { $post_type = array($post_type); } | |
| if ( in_array('property', $post_type)) | |
| { | |
| $join .= " LEFT JOIN {$wpdb->term_relationships} AS avstr ON ({$wpdb->posts}.ID = avstr.object_id) "; | |
| $join .= " LEFT JOIN {$wpdb->term_taxonomy} AS avstt ON (avstr.term_taxonomy_id = avstt.term_taxonomy_id) "; | |
| } | |
| return $join; | |
| }, 10, 2); | |
| // Add a custom ordering clause | |
| add_filter('posts_orderby', function ($orderby, $query) use ($availability_order) | |
| { | |
| global $wpdb; | |
| $post_type = $query->get('post_type'); | |
| if ( !is_array($post_type) ) { $post_type = array($post_type); } | |
| if (in_array('property', $post_type) ) { | |
| // Retrieve the original orderby clause | |
| $original_orderby = $orderby ? $orderby : "{$wpdb->posts}.post_date DESC"; | |
| // Construct the custom order by clause | |
| $order_by_custom = "FIELD(avstt.term_id, " . implode(',', $availability_order) . ")"; | |
| // Combine the custom order by with the original order by | |
| $orderby_combined = "$order_by_custom, $original_orderby"; | |
| return $orderby_combined; | |
| } | |
| return $orderby; | |
| }, 10, 2); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment