Sort posts according to date

时间:2015-09-08 作者:cfnne

我对按日期排序帖子有问题:

现在我的代码:

<?php
global $switched;
$original_blog_id = get_current_blog_id(); // get current blog

$blog_ids = array(4,1);

foreach( $blog_ids as $blog_id ){
switch_to_blog( $blog_id );
$args = array( \'posts_per_page\' => 10, \'orderby\' => \'date\', \'order\' => \'DESC\');
$myposts = get_posts( $args );
foreach ( $myposts as $post ):
setup_postdata( $post ); ?>
<li>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php  endforeach; 
wp_reset_postdata();

switch_to_blog( $original_blog_id ); //switched back to current blog

restore_current_blog();
}
?>
我的问题:

http://images.tinypic.pl/i/00700/vracxlcdm296.png

我想:

http://images.tinypic.pl/i/00700/jo2yp8f83bce.png

我想按所有博客的日期排序。并非每个人都是分开的。

2 个回复
SO网友:Pat J

下面是我如何解决您的问题的(事实上,我想我以前写过这样的代码,但现在找不到):

$blogs = array( 4, 1 );
$all_posts = array();
foreach( $blogs as $blog ) {
    switch_to_blog( $blog );
    $args = array( \'posts_per_page\' => 10, \'orderby\' => \'date\', \'order\' => \'DESC\');
    $blog_posts = get_posts( $args );
    foreach( $blog_posts as $blog_post ) {
        // Add the correct permalink to the Post object
        $blog_post->permalink = get_the_permalink( $blog_post->ID );
        $all_posts[] = $blog_post;
    }
    restore_current_blog();
}

usort( $all_posts, \'__sort_by_date\' );

// Now you can display all your posts

foreach( $all_posts as $post ) {
    setup_postdata( $post );
    the_title( \'<a href="\' . $post->permalink . \'">\', \'</a>\' );
}


function __sort_by_date( $a, $b ) {
    $a_date = strtotime( $a->post_date );
    $b_date = strtotime( $b->post_date );
    if( $a_date === $b_date ) { return 0; }
    if( $a_date > $b_date ) { return 1; }
    return -1;
}
Note: 我已经更新了代码,以便在适当的站点上为每个帖子获得正确的永久链接(根据下面的评论/回答)。

参考文献usort()
  • strtotime()
  • the_title()
  • get_the_permalink()
  • SO网友:Dips Kakadiya

    您可以如下所示为添加参数get_posts 方法

    \'orderby\'          => \'date\',
    \'order\'            => \'DESC\',
    
    有关更多帮助,请访问以下链接https://codex.wordpress.org/Template_Tags/get_posts