get_posts - orderby desc wrong order

5.9k views Asked by At

In my WordPress plugin I am getting posts using the following:

$args = array(
     'post_type' => 'wpplugin_pp_order',
     'posts_per_page' => -1,
     'order' => 'ASC',
     'orderby' => 'ID'
);

$posts = get_posts($args);

The problem is the result is returning like so for the post_id:

3000
3001
3002
3003
2999
2998

How can I put the result the correct order?

3

There are 3 answers

0
Scott Paterson On BEST ANSWER

Found a solution to this problem - (seems like others are also having the same problem - Wordpress get_posts attachments orderby)

The problem is caused by the usort function that extends wp_list_table class. I like most others got this from some online example (everyone seems to be using the same code):

function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'order';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order==='asc') ? $result : -$result;
}

usort($data, 'usort_reorder');

To fix the problem, simply put an if statement around it:

        if (isset($_REQUEST['orderby'])) {
            function usort_reorder($a,$b) {
                $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'order';
                $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
                $result = strcmp($a[$orderby], $b[$orderby]);
                return ($order==='asc') ? $result : -$result;
            }
            usort($data, 'usort_reorder');
        }
0
Ravi Patel On
<?php
        $args = array(
            'post_type' => 'wpplugin_pp_order',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'ID',
            'order' => 'ASC',
        );
        $query = new WP_Query($args);

        if ($query->have_posts()) :
            while ($query->have_posts()) : $query->the_post();

            // your code

            endwhile;
            endif;
            wp_reset_query();

?>          
0
Thiago Gomes On

i found some for you here:

https://wordpress.stackexchange.com/questions/109849/order-by-desc-asc-in-custom-wp-query

Just change 'ASC' for 'DESC' and do it again (:

Let me know if i helped someway.