Skip to content

Displaying Related Posts from Specific Category in Winter Blog Plugin #959

Answered by LukeTowers
01Kuzma asked this question in Q&A
Discussion options

You must be logged in to vote

Do this instead:

PHP Code Section:

function onStart()
{
    // Add the method to the page object so that Twig can access it
    $this->page->addDynamicMethod('getRelatedPosts', [$this, 'getRelatedPosts']);
}

function getRelatedPosts(\Winter\Blog\Models\Post $post, int $limit = 3): iterable
{
    // Get a category to pull related posts from
	$category = $post->categories->first();
    if (!$category) {
        return [];
    }

    // Return the requested number of random published posts
    // from that category and eager load the featured_images
    return $category->posts()
        ->with(['featured_images'])
        ->where('id', '!=', $post->id)
        ->isPublished()
        ->inRa…

Replies: 5 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by LukeTowers
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@LukeTowers
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants