Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MapView_QuasiDistanceOrdering {
- /**
- * Set up a listener to potentially re-order location based search results.
- */
- public function __construct() {
- add_action( 'tribe_events_before_view', array( $this, 'listen' ) );
- }
- /**
- * We can only reorder by distance if the query results contain distance/geodata
- * for each result.
- *
- * @param $template
- */
- public function listen( $template ) {
- global $wp_query;
- if ( empty( $wp_query->posts ) ) return;
- if ( ! $this->are_distances_assigned() ) return;
- $this->quick_sort( $wp_query->posts );
- }
- /**
- * Examine one of the posts in the query results to check if distance info
- * has been assigned.
- *
- * @return bool
- */
- protected function are_distances_assigned() {
- global $wp_query;
- $posts_copy = $wp_query->posts;
- $test_post = array_shift( $posts_copy );
- return isset( $test_post->distance );
- }
- /**
- * Borrows quick sort implementation from previous incarnation
- * of TribeEventsGeoLoc, in turn this borrows from the referenced
- * answer on StackOverflow.
- *
- * @see http://stackoverflow.com/questions/1462503/sort-array-by-object-property-in-php
- * @param $array
- */
- protected function quick_sort( &$array ) {
- $cur = 1;
- $stack[1]['l'] = 0;
- $stack[1]['r'] = count( $array ) - 1;
- do {
- $l = $stack[$cur]['l'];
- $r = $stack[$cur]['r'];
- $cur --;
- do {
- $i = $l;
- $j = $r;
- $tmp = $array[(int) ( ( $l + $r ) / 2 )];
- do {
- /* Divide... */
- while ( $array[$i]->distance < $tmp->distance ) {
- $i ++;
- }
- while ( $tmp->distance < $array[$j]->distance ) {
- $j --;
- }
- /* ...and conquer! */
- if ( $i <= $j ) {
- $w = $array[$i];
- $array[$i] = $array[$j];
- $array[$j] = $w;
- $i ++;
- $j --;
- }
- } while ( $i <= $j );
- if ( $i < $r ) {
- $cur ++;
- $stack[$cur]['l'] = $i;
- $stack[$cur]['r'] = $r;
- }
- $r = $j;
- } while ( $l < $r );
- } while ( $cur != 0 );
- }
- }
- new MapView_QuasiDistanceOrdering;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement