• hi!
    i have an automatic generated array of posts ids. To retrive posts im using query_posts but i want, to get at output posts ordered as the ids. eg.`$arr=array(1,9,7,23,8,11);
    $args = array(
    ‘post__in’ => $arr,
    ‘posts_per_page’ => 7,
    ‘order’
    );
    query_posts($args);`
    but shows display in numerical order,this is 1,7,8,9,11,23.
    Is there a way to display them in way i want?

Viewing 4 replies - 1 through 4 (of 4 total)
  • <?php
    $postids=array(1,9,7,23,8,11);
      foreach ($postids as $id) {
        $post=get_post(intval($id));
        setup_postdata($post);?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      }
    ?>

    There’s an open trac ticket on a similar request:
    http://core.trac.wordpress.org/ticket/13729

    As an alternative, you can cut down on the number of database queries by using this:

    $ids = array(319,589,43,508,531);
    query_posts(array('post__in' => $ids));
    foreach ($wp_query->posts as $p) {
       $posts_by_id[$p->ID] = $p;
    }
    foreach ($ids as $id) {
      if ($post = $posts_by_id[$id]) {
        setup_postdata($post);
        echo '<p>TITLE: ';the_title();echo ' - ';the_ID(); '</p>';
        the_content();
      }
    }

    Even better, this does not copy all the posts into a separate array:

    // Test showing posts by id in an array order.
    $ids = array(319,589,43,508,531);
    query_posts(array('post__in' => $ids, 'posts_per_page' => -1));
    for ($i = 0; $i < sizeof($wp_query->posts); ++$i) {
       $posts_by_id[$wp_query->posts[$i]->ID] = $i;
    }
    foreach ($ids as $id) {
      if ($i = $posts_by_id[$id]) {
        $post = $wp_query->posts[$i];
        setup_postdata($post);
        echo '<p>TITLE: ';the_title();echo ' - ';the_ID(); '</p>';
        the_content();
      }
    }

    Hello
    This code working well. But i can’t get latest one (531).
    Any suggestion?

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘query_posts custom order’ is closed to new replies.