ifusion
ifusion

Reputation: 2233

How to only show blog posts that have a category assigned to them when using the Silverstripe blog module?

I am using the silverstripe blog module: https://github.com/silverstripe/silverstripe-blog

I have blog posts looping out like so:

Blog.ss

<% loop $BlogPosts %>
            <div class="row mtb20">
                <div class="col-md-8">
                    <div class="blog-holder-image" style="background-image: url($FeaturedImage.Fill(700,340).URL);"></div>
                </div>

                    <h2>$Title</h2>

                    <div>
                        <% if $Summary %>
                            $Summary
                        <% else %>
                            <p>$Excerpt</p>
                        <% end_if %>
                    </div>
                    <div>
                        <a class="call-to-action-link" href="$Link">Read more</a>
                    </div>
                </div>
            </div>
<% end_loop %>

At the top of the blog posts, I have a list of categories that you can click on which goes to that category:

 <% if $Categories %>
        <% loop $Categories %>
            <a class="category-btn" href="$Link">$Title</a>
        <% end_loop %>
    <% end_if %>

However the blog posts are not being filtered out, its still showing all the blog posts instead of just the category that has been selected e.g "Design"

If I use the default $PaginatedList method that comes with it it works fine:

<% if $PaginatedList.Exists %>
            <% loop $PaginatedList %>
                <% include PostSummary %>
            <% end_loop %>
        <% else %>
            <p><%t Blog.NoPosts 'There are no posts' %></p>
<% end_if %>

How do I get it to work my way though?

Upvotes: 0

Views: 268

Answers (1)

wmk
wmk

Reputation: 4626

I guess you found the solution yourself... Looking at the code, $BlogPosts gets all child pages - unfiltered. $PaginatedList grabs prefiltered posts by category when you're in the category action in Blog_Controller. The simplest solution would be just to use $PaginatedList, that's how it's supposed to use.

But you might get the $CurrentCategory from the controller and loop over its $BlogPosts relation like

<% loop $CurrentCategory.BlogPosts %>
...
<% end_loop %>

Upvotes: 1

Related Questions