Advertisement
vtxyzzy

Sort on Custom Field presence, date modified

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