Newest posts based on panel hook

Hi,

I have the following hook on page update

kirby()->hook('panel.page.update', function($page) {

try {

	if($page->parent()->intendedTemplate()=='year') {

		$posts = page('home')->newest();
		$postsarray = $posts->yaml();
		$postsarray[] = ['post' => $page->uri()];

		page('home')->update(array(
			'newest' => yaml::encode($postsarray),
		));
	}

} catch(Exception $e) {

	echo $e->getMessage();

}
});

What this basically does: everytime a page is updated the hook will store its URI in an array at the ‘home’ section. This is basically a very simple “newest posts” or “recently edited posts” section I’m working on. So, my question is:

  • How can I check for duplicate entries and replace them or not save anything if the post is already there?

You can use in_array($needle, $haystack)

1 Like

Only add the uri if it is not in the array:

if(! in_array($page->uri(), $postsarray) {
  $postarray[] = ['post' => $page->uri()];
}

Is there a reason why you don’t fetch newest posts by date instead of adding them to a structure field?

1 Like

Well, I wanted to build a special section made of a mix of the newest and recently edited posts but ended up doing something else and using just what you said; fetching and sorting stuff by date.

If you need recently edited post as well, you could use $page->modified() as a filter in addition to filtering by date.