代码之家  ›  专栏  ›  技术社区  ›  MultiDev

如何按顺序循环浏览帖子?

  •  1
  • MultiDev  · 技术社区  · 12 年前

    我在循环浏览Wordpress的帖子,但我需要按照收到的顺序使用数据。我正在查询4个帖子。我需要他们返回的顺序:1,4,2,3,按日期排序。我将尽可能简化以下示例:

    $the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
    
    foreach ($posts as $post) {
    
      echo '<a href="'.get_the_permalink().'" title="'.get_the_title().'" rel="bookmark">'.get_the_title().'</a><br /><br />'; // The actual content is more complicated- keeping it simple for this example
    
    } // end foreach
    

    现在,我该怎么做才能让帖子回复得乱七八糟?(1, 4, 2, 3)

    4 回复  |  直到 12 年前
        1
  •  0
  •   Dave Chen    12 年前

    我有个主意:

    $the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
    $ordered_posts = array();
    
    foreach ($posts as $post)
      $ordered_posts[] = '<a href="'.get_the_permalink().'" title="'.get_the_title().'" rel="bookmark">'.get_the_title().'</a><br /><br />';
    
    $order = array(1, 4, 3, 2);
    $size  = count($order);
    
    for ($i = 0; $i < $size; $i++)
        echo $ordered_posts[$order[$i] - 1];
    

    首先按顺序存储所有帖子,然后使用数组映射序列,可以按修改的顺序输出。

        2
  •  0
  •   Howli    12 年前

    这应该是有效的:

    <?php
    $posts = array();
    $the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
    
    $myposts = get_posts( $the_query);
    foreach ( $myposts as $post ) 
    {
       $posts[] += $post->ID;
    }
    
    echo '<a href="'.get_the_permalink($posts[0]).'" title="'.get_the_title($posts[0]).'" rel="bookmark">'.get_the_title($posts[0]).'</a><br /><br />';
    
    echo '<a href="'.get_the_permalink($posts[4]).'" title="'.get_the_title($posts[4]).'" rel="bookmark">'.get_the_title($posts[4]).'</a><br /><br />';
    
    echo '<a href="'.get_the_permalink($posts[1]).'" title="'.get_the_title($posts[1]).'" rel="bookmark">'.get_the_title($posts[1]).'</a><br /><br />';
    
    echo '<a href="'.get_the_permalink($posts[2]).'" title="'.get_the_title($posts[2]).'" rel="bookmark">'.get_the_title($posts[2]).'</a><br /><br />';
    
    ?>
    
        3
  •  0
  •   Shan Robertson    12 年前

    对于非编程方式,请使用 Simple Custom Post Order 基本上,它允许您在WP后端拖放帖子。非常简单,无需设置。

        4
  •  0
  •   StathisG    12 年前

    您可以尝试以下操作,这将对 $posts 数组中指定的顺序 $order 阵列:

    $the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
    $posts = get_posts($the_query);
    $order = array(1, 4, 2, 3);
    
    usort($posts, function ($a, $b) use ($posts, $order) {
        $a_key = array_search($a, $posts);
        $b_key = array_search($b, $posts);
        $a_order = array_search($a_key + 1, $order);
        $b_order = array_search($b_key + 1, $order);
        return $a_order - $b_order;
    });
    
    foreach ($posts as $post) {
        //do stuff
    }
    

    如果要保留其索引,请使用 uasort 而不是 usort .

    推荐文章