WordPress以任意顺序获取特定帖子

时间:2010-12-01 22:28:58

标签: mysql wordpress select post sql-order-by

现在,我正在做:

$posts = get_posts(array('post_type' => 'page', 'post__in' => array(1, 3, 2, 9, 7)));

我遇到两个问题:

  1. 帖子3是'post_type' => 'post',所以它没有被选中,但我想要它!如果我遗漏'post_type' => 'page',则只选择帖子3(因为它必须假设'post_type'=>'post'。)。
  2. 我希望能够order the posts arbitrarily by their ids。如果我知道如何使用MySQL,我可以这样做:

    SELECT * FROM wp_posts WHERE ID IN (1, 3, 2, 9, 7)
    ORDER BY FIND_IN_SET(ID, '1,3,2,9,7');
    
  3. 但是,我应该如何使用WordPress

3 个答案:

答案 0 :(得分:1)

首先通过他们的ID任意获取所有帖子,然后遍历所有帖子

你可以这样做: -

$posts=$wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE ID IN (1, 3, 2, 9, 7)
ORDER BY FIND_IN_SET(ID, '1,3,2,9,7')");
$count=count($posts);
for ($counter=0 ; $counter < $count; $counter++)
{
   $post=get_post( $posts[$counter]->ID, $output );
  //do your stuffs with posts
}

希望这有帮助

答案 1 :(得分:0)

  1. #wordpress IRC频道上的Kawauso告诉我“post_type需要一系列值。”从那以后,我发现以下内容也选择了帖子3:

  2. 所以,我做了以下事情:

    $post_ids = array(1 => 0, 3 => 1, 2 => 2, 9 => 3, 7 => 4);
    $posts = get_posts(array('post_type' => array('post', 'page'),
                             'post__in' => array_keys($post_ids)));
    $ordered_posts = array(0,0,0,0,0); // size of five; keeps order
    foreach ($posts as $p) {
      setup_postdata($p);
      $ordered_posts[$post_ids[$p->ID]] = array(
        'permalink' => get_permalink($p->ID),
        'title' => $p->post_title,
        'excerpt' => get_the_excerpt(),
        'date' => date('F j, Y', strtotime($p->post_date)));
    }
    

答案 2 :(得分:0)

根据this thread,您可以使用此代码,然后使用经典的WordPress循环:

$args = array(  
'post_type'=>'page',  
    'orderby'=>'menu_order',  
    'order'=>'ASC'  
);  
query_posts($args);