将完整帖子与来自两种不同帖子类型的4个摘录相结合



我正在尝试将最新帖子作为完整帖子。这篇文章可以来自两种不同的帖子类型"帖子"one_answers"教程"。我还想显示四个摘录,其中两个来自"帖子"帖子类型,其中两个来自"教程"帖子类型。我不希望完整的帖子在摘录中重复。

我尝试使用一个WP_QUERY,这几乎使我达到了正确的位置。我还尝试使用多个WP_QUERY,但这并不是那么幸运。

$args  = array(
    'post_type' => array( 'post', 'tutorial' ),
    'post_per_page' => 5
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
    $count = 0;
    while ( $query->have_posts() ) : $query->the_post();
        if ( $count == 0 ) { ?>
            <h2><?php the_title(); ?></h2>
            <?php the_content();
            $count ++;
        } else { ?>
            <h2><?php the_title(); ?></h2>
            <?php the_excerpt();
        }
    endwhile;
endif;
wp_reset_postdata();
?>

所以这个代码使我真的很接近。但是摘录没有做我想要的。我希望它显示两个摘录的"帖子"和两个'教程'的摘录。现在,它显示了一个"教程"的摘录和"邮政"的三个摘录。

任务在一个查询中设置更为复杂。我为您写了一个代码,每个步骤都有评论。请检查一下。

// first get last published post
$last_post = get_posts(
    array(
        'post_type' => array( 'post', 'tutorial' ),
        'numberposts' => 1
    )
);
// get two posts excluding $last_post which might be a post
$last_two_posts = get_posts(
    array(
        'post_type' => array( 'post' ),
        'numberposts' => 2,
        'exclude' => array($last_post[0]->ID)
    )
);
// get two tutorial excluding $last_post which might be a tutorial
$last_two_tutorials = get_posts(
    array(
        'post_type' => array( 'tutorial' ),
        'numberposts' => 2,
        'exclude' => array($last_post[0]->ID)
    )
);
$posts = array_merge($last_post, $last_two_posts, $last_two_tutorials);
foreach( $posts as $post ) {
    setup_postdata($post);
    // print content only for first post and excerpt for others
    if ($post->ID == $last_post[0]->ID) {
        the_content();
    } else { 
        if($post->post_type == 'post') {
            echo '<div class="post-excerpt">' . get_the_excerpt() . '</div>';
        } else {
            echo '<div class="tutorial-excerpt">' . get_the_excerpt() . '</div>'; 
        }
    }
}
wp_reset_postdata();

最新更新