Render recent post in page?

I have a need to display the 5 most recent posts from my blog on a number of pages. Things like on the 404 page “can’t find what you’re looking for? Here’s some recent posts” and on the search page etc.

First of all, I’m not sure how to render the required PHP within a textarea or markdown field. Is that even possible? Whenever I try, it just outputs the code in plaintext.

Secondly, I obviously don’t want to re-use the code, so it would be better to have something like a snippet, but they’re obviously for templates. So can I do this too?

Thanks!

You cannot render PHP in a field.

Sounds as if you do want to reuse the code… :wink:

Yes.

Ok, so if you really want to refer to a snippet at random places in your textarea fields, then I’d use a custom Kirbytag that is replaced with the content of the snippet at runtime

Snippet, e.g. recent-posts.php

<?php
$lastPosts = page('blog')->children()->listed()->sortBy('date', 'desc')->limit($limit);
// then loop through the posts and render your html

Create a custom Kirbytag called snippet, can be pretty straightforward, but you can extend it, for example with a limit attribute to control the number of posts to show from the tag:

<?php

use Kirby\Cms\App as Kirby;

Kirby::plugin('your/plugin', [
    'tags' => [
        'snippet' => [
            'attr' => [
              'limit',
            ],
            'html' => function($tag) {
                return snippet($tag->value(), ['limit' => $tag->limit ?? 5], true);
            }
        ]
    ]
]);

Call in your textarea

(snippet: recent-posts)

Sooooo it kinda worked. What it does now is renders the 5 latest posts as a code block. It renders it correctly, but it’s a code block.

Here’s a screenshot which hopefully helps explain:

I’m using fabianmichael/kirby-markdown-field, not sure if that has anything to do with it?

I’ve managed to work around it in a way that I think it probably a better solution anyway. Rather than wedge this in with a plugin, I just created another template with the lastest-posts snippet added to the end of the content.

Thanks for the continues help, Sonja. I know you’re probably sick of me by now. :slight_smile: