简体   繁体   中英

Can't order wordpress posts

I have there the code I'm using, and I'm trying to get the posts in the order of the IDs from the $menus array but don't do that, he gave me the posts from the newest to oldest...I have tried to use order with DESC but the array did not change.

$menus = array(105, 54, 111);
       $args = array(
        'post__in' => $menus,
        'orderby' => 'ID',
        'order'   => 'DESC',
    );
    $query = new WP_Query( $args );

    if ( $query->have_posts() ) :
    $i = 1;
    while ( $query->have_posts() ) : $query->the_post();
    do_action('fwp_before_post_content');
        get_template_part('extend-helpers/' . $layout);
    do_action('fwp_after_post_content');
    $i++;
    endwhile;
    else:
        get_template_part('extend-helpers/content', 'none');
    endif;

UPDATE:

The posts are from different categories.

UPDATE II:

SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.ID IN (105,54,111) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.menu_order, FIELD( wp_posts.ID, 105,54,111 ) LIMIT 0, 1000" 

Why I have ORDER BY wp_posts.menu_order ? because in $args I don't have orderby menu_order..

You need to add the "orderby" item in the args you pass WP_Query.

You can find the documentation here

Have you seen the WP_query loop? https://code.tutsplus.com/tutorials/mastering-wp_query-using-the-loop--cms-23031 . It uses $args=ASC and DSC and 'orderby ' =>'id' too.

for the first part, you want to use post__in also in orderby line as Juan suggested in his comment. From the documentation: 'post__in' - Preserve post ID order given in the 'post__in' array. So, your code should look like this

    $menus = array(55, 53, 57); // I have used mine ids
    $args = array(
        'post__in' => $menus,
        'orderby' => 'post__in',
    );
    $query = new WP_Query( $args );

For the second part, which is more important, why do you have ORDER BY wp_posts.menu_order. You can find answer also in comments. The query is being altered by something (theme or plugin), check pre_get_posts hook, try switching theme, etc.

I have tested this code and it is working, so it is ordering posts as they are in array $menus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM