Advertisement
helgatheviki

Sort posts by optional meta key then by post date

Oct 8th, 2014
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.73 KB | None | 0 0
  1. // filter the posts clauses for some shenanigans
  2. // order by an option meta field and then by post date
  3. add_filter( 'posts_clauses', 'kia_edit_posts_clauses', 10, 2 );
  4.  
  5. function kia_edit_posts_clauses( $pieces, $query ) {
  6.    
  7.     if ( $query->get( 'orderby' ) == 'dealer_date' && isset( $query->query_vars['query_id'] ) && $query->query_vars['query_id'] == "woocommerce_my_account_my_orders_query" ) {
  8.  
  9.             global $wpdb;
  10.  
  11.             // join the post_meta table
  12.             $pieces[ 'join' ] .= $wpdb->prepare( ' LEFT JOIN ' . $wpdb->postmeta . ' dealer_pm ON dealer_pm.post_id = ' . $wpdb->posts . '.ID AND dealer_pm.meta_key = %s AND LENGTH(TRIM(dealer_pm.meta_value) )', '_shipping_dealer_number' );
  13.                        
  14.             // Negate the meta_value if it exists to sort before zero.
  15.             $pieces[ 'fields' ] .= ', CASE WHEN dealer_pm.meta_value IS NOT NULL THEN -dealer_pm.meta_value ELSE 0 END AS dealer_number';
  16.  
  17.             $pieces[ 'orderby' ] = $pieces[ 'orderby' ] = 'ISNULL(MAX(dealer_pm.meta_value)) OR LENGTH(TRIM(MAX(dealer_pm.meta_value))) = 0 ASC, MAX(dealer_pm.meta_value) ASC,' . $wpdb->posts . '.post_date DESC';
  18.            
  19.         }
  20.  
  21.         return $pieces;
  22.     }
  23.  
  24.  
  25. // then my query
  26. $customer_orders = get_posts( apply_filters( 'woocommerce_my_account_my_orders_query', array(
  27.     'query_id' => 'woocommerce_my_account_my_orders_query',
  28.     'posts_per_page' => $order_count,
  29.     'no_found_rows' => true,
  30.     'date_query' => array(
  31.         array(
  32.             'after' => '2 months ago',
  33.             ),
  34.     ),
  35.     'meta_query' => array(
  36.         array(
  37.             'key'     => '_customer_user',
  38.             'value'   => get_current_user_id(),
  39.             'compare' => '=',
  40.         ),
  41.     ),
  42.     'post_type'   => wc_get_order_types( 'view-orders' ),
  43.     'post_status' => array_keys( wc_get_order_statuses() ),
  44.     'suppress_filters' => false,
  45.     'orderby' => 'dealer_date'
  46. ) ) );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement