Search code examples
phpjsonwordpressloopsposts

Can't loop through posts inside a category loop. Only get the first item


I'm trying to build a custom json feed for wordpress with php.

It is already done as you can see.

The problem is that the loop through posts only output one item from the same category.

Here is my php code:

<?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);
?>

Any idea? Thanks.


Solution

  • That is because you are saying to only print it once. Adding a while statement should work:

    $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++;
    }
    

    EDIT: This should work

    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;