Get post variables within controller

I’m new to Sage 9 and blade/controllers. I have been persisting for a while and managed to get my first Sage 9 project going. I have been looking right through SoberWP but I can’t seem to find out a solution to my issue.

I want to use to query posts using the page slug as the ‘category_name’ from the App Controller (Is this the right terminology?) Example: Page is called ‘Foo’, I want to display Posts that are in the category which is also called ‘Foo’.

I don’t know how to pull/get in the page slug as the context of the page? I have a feeling I have over thought this and would appreciate some ideas as this project moves into overtime.

public function links() {
    $links = get_posts([
        'post_type'      => 'post',
        'orderby'        => 'DESC',
        'posts_per_page' => 10,
        'category_name'  => ?,
    ]);
    return array_map(function ($post) {
        return [
            'title'  => $post->post_title,
            'link'   => get_permalink($post->ID),
        ];
    }, $links);
}

Controller

public function links() 
{
    return collect(get_posts([
        'post_type' => 'post',
        'posts_per_page' => 10,
        'category_name' => get_post()->post_name,
    ]))->map(function ($post) {
        return (object) [
            'title' => get_the_title($post),
            'url' => get_permalink($post),
        ];
    });
}

View

@foreach ($links as $link)
    <h2>
        <a href="{{ $link->url }}">{{ $link->title }}</a>
    </h2>
@endforeach

Something like this should work.

7 Likes

Oh Mate. You are awesome. Thank you so much.

get_post() - I should have thought of that.

This topic was automatically closed after 42 days. New replies are no longer allowed.