I am creating a 'loop' that needs to display pages (not posts) in a defined order of ids. What I did till now is:

$ids = array(434, 814, 3660, 3235, 99, 1002, etc.);

add_filter('posts_orderby', 'enforce_specific_order');

function enforce_specific_order($orderby) {
    global $wpdb;
    $ids_as_text = join(",",$ids);
    return "FIND_IN_SET(".$wpdb->posts.".ID, '".$ids_as_text."') ASC";

global $post;
$args = array( 'posts_per_page' => 20, 'post_type' => 'page', 'post__in' => $ids );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); ?>

<h2><?php the_title(); ?></h2>

<?php endforeach; remove_filter( current_filter(), __FUNCTION__ ); wp_reset_postdata(); ?>

I can see the pages titles correctly displayed but not in the order I am expecting based on the $ids.

Any idea?

1 Answer 1


Instead, you should use WP_Query

Something like so:

$specific_order_pages_query_args = array(
    'post_type' => 'page',
    'post__in'  => $ids,
    'orderby'   => 'post__in'

$specific_order_pages_query = new WP_Query( $specific_order_pages_query_args );

WP_Query's order value post__in is a special value to order by the supplied post__in ID's

See more under Order in WP_Query http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.