Advertisement
vtxyzzy

Sort on Custom Field presence

Mar 9th, 2012
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.65 KB | None | 0 0
  1. // Sort posts from last 24 hrs in order on presence of a custom field, then date
  2. $meta_key = 'featured';  // The meta_key
  3.  
  4. function mam_posts_fields ($fields) {
  5.    global $mam_global_fields;
  6.    // Make sure there is a leading comma
  7.    if ($mam_global_fields) $fields .= (preg_match('/^(\s+)?,/',$mam_global_fields)) ? $mam_global_fields : ", $mam_global_fields";
  8.    return $fields;
  9. }
  10. function mam_posts_join ($join) {
  11.    global $mam_global_join;
  12.    if ($mam_global_join) $join .= " $mam_global_join";
  13.    return $join;
  14. }
  15. function mam_posts_where ($where) {
  16.    global $mam_global_where;
  17.    if ($mam_global_where) $where .= " $mam_global_where";
  18.    return $where;
  19. }
  20. function mam_posts_orderby ($orderby) {
  21.    global $mam_global_orderby;
  22.    if ($mam_global_orderby) $orderby = $mam_global_orderby;
  23.    return $orderby;
  24. }
  25. add_filter('posts_fields','mam_posts_fields');
  26. add_filter('posts_join','mam_posts_join');
  27. add_filter('posts_where','mam_posts_where');
  28. add_filter('posts_orderby','mam_posts_orderby');
  29.  
  30. global $wpdb,$wp_query;
  31. $now = date('Y-m-d',(time() - 60*60*24));
  32.  
  33. $mam_global_fields = ', IF(ISNULL(pm.meta_id),9,1) as sort_key';
  34. $mam_global_join = " LEFT JOIN $wpdb->postmeta pm ON ($wpdb->posts.ID = pm.post_id AND pm.meta_key = '$meta_key')";
  35. $mam_global_where = " AND $wpdb->posts.post_date > '$now' ";
  36. $mam_global_orderby = "sort_key, $wpdb->posts.post_date DESC";
  37. query_posts('posts_per_page=-1&ignore_sticky_posts=1');
  38. //echo 'REQUEST: ';print_r($wp_query->request);
  39. if (have_posts()) {
  40.    while (have_posts()) {
  41.       the_post();
  42.            echo "<p>"; the_title(); echo ' '; the_time('Y-m-d');  echo " $post->sort_key</p>";
  43.    }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement