Advertisement
vtxyzzy

Sort on presence of Custom Field, field value, then date

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