foreach 循环 returns 只有一个结果 post

foreach loop returns only one result of post

我正在尝试显示每个类别中的 4 个 post。试过这段代码,它应该从各个类别中获取 4 posts。然后按要求在 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);
        }   
    }

然后在输出中,它只显示每个类别的一个结果(post),但它应该显示 4.

<?php foreach($col1 as $item) { ?>
    <li>
    <p><?= $item['name']; ?></p>
    <a href="<?php  echo $link;  ?>"><?= $item['post_title']; ?></a>    
    </li>
<?php } ?>

您正在检索 $posts 的数组,但您只是将第一个元素 $posts[0] 添加到 $data 数组。

你需要用 foreach

循环它们
$posts = get_posts(
    array(
        'cat' => $cat_id,
        'tax_query' => array(
            array(
                'posts_per_page' => 4,
                'taxonomy' => 'parsha',
                'field' => 'term_id',
                'terms' => $term->term_id,
            )
        )
    )
);

foreach($posts as $post) {
    $data = array(
        'term_id'    => $term->term_id,
        'name'       => $term->name,
        'order'      => $order,
        'column'     => $column,
        'post_ids'   => $post->ID,
        'post_title' => $post->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);
    }   
}