SHARE
TWEET

Relevanssi Custom Meta Ordering of Search Results

a guest Apr 18th, 2013 367 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Adds a custom field to all posts, with the unixtime of a custom date OR the published date
  3.  *
  4.  * @param int $postId
  5.  */
  6. function customDateField($postId)
  7. {
  8.     // Generate my unix time
  9.     $customDate = get_field('date');
  10.     $searchDate = ($customDate) ? date('U', strtotime($customDate)) : get_post_time('U', TRUE);
  11.     // You never need to add the post_meta, this will add it if needed
  12.     update_post_meta($postId, 'searchdate', $searchDate);
  13.     remove_filter('save_post', 'customDateField');
  14. }
  15.  
  16. add_filter('save_post', 'customDateField');
  17.  
  18. /**
  19.  * Allows the ordering by custom terms
  20.  *
  21.  * @param array $hits
  22.  *
  23.  * @return array mixed
  24.  */
  25. function customDateSearch($hits)
  26. {
  27.     if (get_query_var('orderby') == 'searchdate') {
  28.         $dates = array();
  29.         foreach ($hits[0] as $hit) {
  30.             $searchdate = get_post_meta($hit->ID, 'searchdate', TRUE);
  31.             if (!isset($dates[$searchdate])) {
  32.                 $dates[$searchdate] = array();
  33.             }
  34.             array_push($dates[$searchdate], $hit);
  35.         }
  36.         ksort($dates);
  37.         $sorted_hits = array();
  38.         foreach ($dates as $searchdate => $searchdate_hits) {
  39.             $sorted_hits = array_merge($sorted_hits, $searchdate_hits);
  40.         }
  41.         // By default everything is sorted ascending, check if we need to change
  42.         $hits[0] = ('asc' == strtolower(get_query_var('order'))) ? array_reverse($sorted_hits) : $sorted_hits;
  43.     }
  44.     return $hits;
  45. }
  46.  
  47. add_filter('relevanssi_hits_filter', 'customDateSearch');
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top