在首页按日期排列帖子

时间:2012-12-30 作者:risto

我有代码显示头版上每个类别的最后5篇帖子。然而,目前它们是按类别排序的。是否可以按发布日期订购,但每个类别仍有5篇文章?

这是我当前的代码:

$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
if( $cats = get_categories() ) foreach( $cats as $cat ) :
//go through all site\'s categories and get up to 5 posts each////

    $cat_query = new WP_Query( array(
        \'post__not_in\' => get_option( \'sticky_posts\' ),
        \'category__in\' => array($cat->term_id),
        \'posts_per_page\' => 5,
        \'paged\' => $paged
        ) );

        if($cat_query->have_posts()) : ?>
<h3 class="cat-title"><?php echo $cat->name; ?></h3>
        <?php while ($cat_query->have_posts()) : $cat_query->the_post();
        get_template_part( \'loop\', \'index\' );

        endwhile; endif; wp_reset_postdata();
endforeach;

1 个回复
SO网友:stealthyninja

添加orderbyorder 针对您的论点:

$cat_query = new WP_Query( array(
    \'post__not_in\' => get_option( \'sticky_posts\' ),
    \'category__in\' => array($cat->term_id),
    \'posts_per_page\' => 5,
    \'paged\' => $paged,
    \'orderby\' => \'date\',
    \'order\' => \'DESC\'
) );

Update

似乎它仍然需要一个类别,列出5个帖子,然后转到另一个类别,有5个帖子等等。它需要最后的帖子,但它们是一个又一个类别列出的

请尝试以下操作:

$paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;

$i = 0;

if ( $cats = get_categories() ) foreach( $cats as $cat ) :
    $cat_query = new WP_Query( 
        array(
            \'post__not_in\' => get_option( \'sticky_posts\' ),
            \'category__in\' => array ( $cat->term_id ),
            \'posts_per_page\' => 5,
            \'paged\' => $paged,
            \'orderby\' => \'date\',
            \'order\' => \'DESC\'
        )
    );

    if ( $cat_query->have_posts() ) : ?>
        <?php while ( $cat_query->have_posts() ) : $cat_query->the_post();
            // arrays of all the posts\' IDs and dates
            $the_posts[\'ID\'][$i] = $post->ID;
            $the_posts[\'date\'][$i] = $post->post_date;

            $i++;
        endwhile;
    endif; wp_reset_postdata();
endforeach;

foreach ( $the_posts[\'date\'] as $the_post_date ) {
    $post_dates[] = $the_post_date;
}

// sort all the posts by their dates
array_multisort( $post_dates, SORT_DESC, $the_posts[\'ID\'] );

foreach ( $the_posts[\'ID\'] as $the_post_id ) {
    $post_ids[] = $the_post_id;
}

$query = new WP_Query( array( \'post_type\' => \'post\', \'post__in\' => $post_ids ) );

if ( $query->have_posts() ) : ?>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
    <h3 class="cat-title"><?php $cat = get_the_category( get_the_ID() ); echo $cat[0]->name; ?></h3>
    <?php
        get_template_part( \'loop\', \'index\' );
    endwhile;
endif; wp_reset_postdata();

结束

相关推荐

Hook into WordPress update?

我想知道是否有任何方法可以连接到WordPress更新过程并发送$_POST 要更新服务器的变量?我正在从私有服务器上提供插件/主题更新,并将其与以下内容挂钩:add_filter(\'pre_set_site_transient_update_themes\', \'check_for_update\');这很好用。新版本的主题/插件显示在“Dashboard”>“update”下,我可以更新。但问题是,我希望用户只有在提供了正确的登录/密码(首先通过add_option()). 理想情况下,除非