您可能已经解决了这个问题,但这里有两个例子可以说明如何做到这一点。在我的两个示例中,我首先进行排序,然后进行渲染。在我看来,这让事情变得越来越清晰。
Example 1
循环查询的帖子并将其排序为两个助手数组。如果这些数组有贴子,请循环它们并渲染贴子。
$posts = helper_function_to_query_posts();
$future_posts = array();
$past_posts = array();
$today = strtotime(\'today\');
foreach ($posts as $post) {
if ( $post->post_date >= $today ) {
$future_posts[] = $post;
} else {
$past_posts[] = $post;
}
}
if ( $future_posts ) {
esc_html_e( \'Upcoming Posts\', \'sage\' );
helper_function_to_handle_looping_and_rendering_of_posts( $future_posts );
}
if ( $past_posts ) {
esc_html_e( \'Past Posts\', \'sage\' );
helper_function_to_handle_looping_and_rendering_of_posts( $past_posts );
}
Example 2
循环查询的帖子并将帖子html推送到助手变量中。之后回显这些变量。
$posts = helper_function_to_query_posts();
$future_posts_html = \'\';
$past_posts_html = \'\';
$post_html_template = \'<div class="my-post">
<h2>%s</h2>
%s
</div>\';
$today = strtotime(\'today\');
foreach ($posts as $post) {
if ( $post->post_date >= $today ) {
$future_posts_html .= sprintf(
$post_html_template,
esc_html($post->post_title),
esc_html($post->post_excerpt),
);
} else {
$past_posts[] = .= sprintf(
$post_html_template,
esc_html($post->post_title),
esc_html($post->post_excerpt),
);
}
}
if ( $future_posts_html ) {
esc_html_e( \'Upcoming Posts\', \'sage\' );
echo $future_posts_html;
}
if ( $past_posts_html ) {
esc_html_e( \'Past Posts\', \'sage\' );
echo $past_posts_html;
}