Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

<?php
$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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer
    
Thank you, it works! –  Randomize Oct 31 '13 at 13:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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