foreach循环只返回一个post结果
我试图显示每个类别的 4 个帖子。尝试过这段代码,它应该从各自的类别中获取 4 个帖子。然后按 col1、col2 等中的要求对它们进行排序。
<?php
$col1 = $col2 = $col3 = $col4 = $col5 = array();
$parsha_terms = get_terms('parsha');
foreach($parsha_terms as $term) {
$order = get_field('parsha_order', 'term_' . $term->term_id);
$column = get_field('parsha_column', 'term_' . $term->term_id);
$color_pdf = get_field('pdf', 'term_' . $term->term_id);
$posts = get_posts(
array(
'cat' => $cat_id,
'tax_query' => array(
array(
'posts_per_page' => 4,
'taxonomy' => 'parsha',
'field' => 'term_id',
'terms' => $term->term_id,
)
)
)
);
$data = array(
'term_id' => $term->term_id,
'name' => $term->name,
'order' => $order,
'column' => $column,
'post_ids' => $posts[0]->ID,
'post_title' => $posts[0]->post_title,
'color_pdfs' => $pdfcolor,
'color_pdf_link' => $color_pdf,
);
if($column == 1) {
array_push($col1, $data);
}
else if($column == 2) {
array_push($col2, $data);
}
else if($column == 3) {
array_push($col3, $data);
}
else if($column == 4) {
array_push($col4, $data);
}
else if($column == 5) {
array_push($col5, $data);
}
}
然后在输出中,它只显示每个类别的一个结果(帖子),但它应该显示 4。
<?php foreach($col1 as $item) { ?>
<li>
<p><?= $item['name']; ?></p>
<a href="<?php echo $link; ?>"><?= $item['post_title']; ?></a>
</li>
<?php } ?>
I'm trying to show 4 posts from each category. Tried this code which should fetch 4 posts from respective categories. then sort them as required in col1, col2, and so on.
<?php
$col1 = $col2 = $col3 = $col4 = $col5 = array();
$parsha_terms = get_terms('parsha');
foreach($parsha_terms as $term) {
$order = get_field('parsha_order', 'term_' . $term->term_id);
$column = get_field('parsha_column', 'term_' . $term->term_id);
$color_pdf = get_field('pdf', 'term_' . $term->term_id);
$posts = get_posts(
array(
'cat' => $cat_id,
'tax_query' => array(
array(
'posts_per_page' => 4,
'taxonomy' => 'parsha',
'field' => 'term_id',
'terms' => $term->term_id,
)
)
)
);
$data = array(
'term_id' => $term->term_id,
'name' => $term->name,
'order' => $order,
'column' => $column,
'post_ids' => $posts[0]->ID,
'post_title' => $posts[0]->post_title,
'color_pdfs' => $pdfcolor,
'color_pdf_link' => $color_pdf,
);
if($column == 1) {
array_push($col1, $data);
}
else if($column == 2) {
array_push($col2, $data);
}
else if($column == 3) {
array_push($col3, $data);
}
else if($column == 4) {
array_push($col4, $data);
}
else if($column == 5) {
array_push($col5, $data);
}
}
then in output, it shows only one result(post) of each category, but it should show 4.
<?php foreach($col1 as $item) { ?>
<li>
<p><?= $item['name']; ?></p>
<a href="<?php echo $link; ?>"><?= $item['post_title']; ?></a>
</li>
<?php } ?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在检索
$posts
数组,但随后仅将第一个元素$posts[0]
添加到$data
数组中。您需要使用
foreach
循环它们You're retrieving an array of
$posts
but you're then only adding the first element$posts[0]
to your$data
array.You need to loop them with
foreach