0

I need to list posts in a very specific order that has nothing to do with the date of the posts or the title, or anything WordPress can figure out for me. I need this order to be used when I list posts in a category and on the category archive page itself.

Is it possible to do something like this, were $idlist was an array of post ids in the order I want, and it could loop through each one?

  <?php query_posts(post_id=$idlist); ?>
  <?php the_permalink(); ?> etc...

1 Answer 1

4

First off, query_posts is terrible doesn't use it. It does all kinds of fun things like mess up the very useful conditional tags like is_singular and the like as well as mess up pagination.

Short of hooking into the posts_orderby filter and writing some custom order by SQL, your best bet is to use the post__in argument combined with the post__in orderby argument that was added in WP 3.5.

Example:

<?php
$custom_query = new WP_Query(array(
    'post__in'  => array(1, 2, 4, 5, /* whatever your post ID's are here */),
    'orderby'   => 'post__in',
));

while ($custom_query->have_posts()) {
    $custom_query->the_post();
    // use the normal template tags here
    ?>
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    <?php
}

// restore the original query
wp_reset_query();
1
  • Perfect. I put my final code in a gist for my own benefit and in case anyone is interested.
    – JPollock
    Commented Mar 3, 2013 at 21:32

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.