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' ); 

Related posts

Leave a Reply

3 comments

  1. 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' )
    );
    
  2. 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 .