Php Can';t循环通过类别循环中的帖子。仅获取第一项

Php Can';t循环通过类别循环中的帖子。仅获取第一项,php,json,wordpress,loops,posts,Php,Json,Wordpress,Loops,Posts,我正在尝试用php为wordpress构建一个自定义json提要 正如你所看到的,已经完成了 问题是,循环通过POST只输出同一类别的一个项目 以下是我的php代码: <?php header("Content-type: application/json"); class Item { public $id = ""; public $title = ""; public $thumb = ""; }

我正在尝试用php为wordpress构建一个自定义json提要

正如你所看到的,已经完成了

问题是,循环通过POST只输出同一类别的一个项目

以下是我的php代码:

<?php
    header("Content-type: application/json");

    class Item {
        public $id = "";
        public $title  = "";
        public $thumb = "";
    }

    class Category {
        public $id = "";
        public $title = "";
        public $item = array();
    }    

    $finalData = array();
    //Get sub-categories from 'news'
    $idObj = get_category_by_slug('news'); 
    $id = $idObj->term_id;
    $cat_args=array(
        'orderby' => 'id',
        'order' => 'ASC',
        'parent' => $id
    );

    $categories=get_categories($cat_args);

    //Loop through categories
    foreach($categories as $category) {
        $args=array(
            'showposts' => 10,
            'category__in' => array($category->term_id),
            'caller_get_posts'=>1
        );
        $posts=get_posts($args);
        $a = new Category();
        $a->id = $category->term_id;
        $a->title  = $category->name;
        $arrayForItems = array();

        //Loop through first 10 posts from this categorie
        if ($posts) {
            $actualItem = $arrayForItems[] = new Item();
            $actualItem->id = get_the_ID();
            $actualItem->title = get_the_title();
            $img = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'appthumb' );
            $actualItem->thumb = $img;
        }
        $a->item = $arrayForItems;
        $finalData[] = $a;
    };

    echo json_encode($finalData);
?>


有什么想法吗?谢谢。

那是因为你说只打印一次。添加while语句应该可以:

$count = 0;
while($count < 10)
{
    if ($posts) {
            $actualItem = $arrayForItems[] = new Item();
            $actualItem->id = get_the_ID();
            $actualItem->title = get_the_title();
            $img = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'appthumb' );
            $actualItem->thumb = $img;
     }
     $count++;
}

foreach循环更适合这种情况,不是吗?谢谢Howlin。现在我可以得到10个职位,每个类别,但职位总是一样的!有什么想法吗?
foreach ($posts as $post):
 setup_postdata($post);
        //Loop through first 10 posts from this categorie
        if ($posts) {
            $actualItem = $arrayForItems[] = new Item();
            $actualItem->id = get_the_ID();
            $actualItem->title = get_the_title();
            $img = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'appthumb' );
            $actualItem->thumb = $img;
        }
        $a->item = $arrayForItems;
        $finalData[] = $a;
 endforeach;