提问人:user13286 提问时间:4/9/2022 更新时间:4/9/2022 访问量:176
PHP 在 while 循环中设置两个具有不同内容的输出缓冲区
PHP setting up two output buffers with different contents in while loop
问:
我有一个 Wordpress 网站,我正在尝试在 AJAX 调用中循环我的帖子,我想将循环中第一篇文章的 HTML 存储在一个与其他帖子不同的变量中。我将如何设置输出缓冲区
if (have_posts()) :
$i = 0;while(have_posts()): the_post();
if ($i == 0):
ob_start();
get_template_part('templates/latest-post', get_post_format());
$recent_post = ob_get_contents();
ob_end_clean();
else:
ob_start();
get_template_part('templates/remaining-posts', get_post_format());
$remaining_posts = ob_get_contents();
ob_end_clean();
endif;
$i++; endwhile;
endif;
这是行不通的,因为每次迭代都会调用 and,所以我最终在变量中只有 1 个帖子,但我不确定如何正确设置它。ob_start
ob_clean
$remaining_posts
答:
1赞
Chris Haas
4/9/2022
#1
您可以使用以下命令连接该内容:.=
// Initialize the remaining posts variable
$remaining_posts = '';
if (have_posts()) :
$i = 0;while(have_posts()): the_post();
if ($i == 0):
ob_start();
get_template_part('templates/latest-post', get_post_format());
$recent_post = ob_get_contents();
ob_end_clean();
else:
ob_start();
get_template_part('templates/remaining-posts', get_post_format());
// Concatenate
$remaining_posts .= ob_get_contents();
ob_end_clean();
endif;
$i++; endwhile;
endif;
评论
$remaining_posts .= ob_get_contents()
$remaining_posts