Crerem
Crerem

Reputation: 1359

WP_Query orderby meta_key and id

I'm trying to make a wp_query get the last x posts order by a meta_value and ID. The prop_featured value can be 1 or 0 . I want to get the list of post with the ones having prop_featured=1 as the first ones and then the others ordered by ID. Here is my arg array :

           $args = array(
            'post_type'         => $type,
            'post_status'       => 'publish',
            'paged'             => 0,
            'posts_per_page'    => 10,
            'meta_key'          => 'prop_featured',
            'orderby'           => 'meta_value ID',
            'order'             => 'DESC'

        );

I also try using filters

         function my_order($orderby) { 
         global $wpdb; 
         $orderby = 'wp_postmeta.meta_value, wp_posts.ID DESC';
         return $orderby;
         } 

   add_filter( 'posts_orderby', 'my_order' ); 
   $recent_posts = new WP_Query($args);
   remove_filter( 'posts_orderby', 'my_order' ); 

Upvotes: 2

Views: 12028

Answers (3)

Patrick
Patrick

Reputation: 339

To my mind, the easiest solution is to replace your initial orderby by an array (and delete your order entry), like this:

$args = array(
    'post_type'      => $type,
    'post_status'    => 'publish',
    'paged'          => 0,
    'posts_per_page' => 10,
    'meta_key'       => 'prop_featured',
    'orderby'        => array( 'meta_value_num' => 'DESC', 'ID' => 'DESC' )
);

Upvotes: 4

Crerem
Crerem

Reputation: 1359

The solution was to work with filters. My mistake is i didn't put the order after each parameter Instead of wp_postmeta.meta_value, wp_posts.ID DESC' it should be 'wp_postmeta.meta_value DESC, wp_posts.ID DESC';

Here is the correct code :

      add_filter( 'posts_orderby', 'my_order' ); 
      $recent_posts = new WP_Query($args);
      remove_filter( 'posts_orderby', 'my_order' ); 

     function my_order($orderby) { 
       global $wpdb; 
       $orderby = 'wp_postmeta.meta_value DESC, wp_posts.ID DESC';
     return $orderby;
      } 

Hope it helps .

Upvotes: 0

Anastis
Anastis

Reputation: 256

Try replacing 'orderby' => 'meta_value ID', with 'orderby' => 'meta_value_num ID',

Upvotes: 0

Related Questions