Include posts of subpage in json output

I’ve been following the doc on generating JSON with Kirby and have been struggling getting it to generate the output – as it is right now, I have it properly outputting all of my top level posts…but i’d love if it also grabbed the children of my one sub-page.

My site is arranged like this– the subpage posts are only shown on the subpage, and the regular posts are shown on the homepage. I’d like the json to be outputted in a similar format…but if not possible, is there a quicker way to change $data = $pages->find('posts')->children()->visible()->flip(); to show just the sub-page posts? I’m not great at this syntax and have been trying variations of $pages ->find(‘feed’)->children and striking out…

Page (Chris)
     a. Sub-Page (Feed)
              i. sub-page article 
           ii. sub-page article
          iii. sub-page article (x20)
    b. Article
    c. Article
    d. Article (x2)

This is what I’ve got right now:

<?php

header('Content-type: application/json; charset=utf-8');

$data = $pages->find('posts')->children()->visible()->flip();
$json = array();

foreach ($data as $article) {
    $json[] = array(
    'url'   => (string)$article->url(),
    'title' => (string)$article->title(),
    'date'  => (string)$article->date(),
    'categories' => (array)$article->categories()->split(),

  );
}

echo json_encode($json, JSON_PRETTY_PRINT);

You could probably use filterby() like this, assuming all the pages you do want have a template called posts:

$data = $site->index()->filterBy('template', 'posts')->visible()->flip();

you can do more then one template:

$data = $site->index()->filterBy('template', 'in', ['article', 'project'])->visible()->flip();

For more information on filtering, see here and here.

When Ive done similar things myself, i ended up using multiple foreach loops for each sub section i wanted to add to the array.

Oh great, filtering worked – thank you! I wasn’t able to get it working as subarray within the full list of posts, but this is more than good enough for what I need :slight_smile:

Depending on how many (other) pages and subpages your site has, going through the complete index ($site->index()) might id not the most performant way of doing things.

You can instead use the page index and exclude the feed page:

$data = page('posts')->index()->not('feed');

If you let me know what you want the final Json output to look like, I think we can find a solution for that as well.