0
我正嘗試爲php構建一個自定義的json feed。無法循環通過類別循環內的帖子。只獲得第一個項目
它已經完成,你可以看到。
問題是,通過帖子循環只輸出同一類別的一個項目。
這裏是我的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);
?>
任何想法?謝謝。
foreach循環更適合這種情況下,不是嗎? – 2014-09-03 10:41:43
謝謝Howlin。現在,我可以爲每個類別獲得10個帖子,但帖子總是相同的!任何想法? – 2014-09-03 10:45:24
@RafaelMartins,檢查我的編輯,應該工作。 – Howli 2014-09-03 11:42:46