Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Blog Module /

Discuss the Blog Module.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

How to display recent posts in sidebar on Blog page [SOLVED]


Go to End


2 Posts   1430 Views

Avatar
Tobyc

Community Member, 2 Posts

18 June 2016 at 6:44pm

Edited: 27/06/2016 1:10am

Hi,

I am trying to display a list of recent posts on the Blog page. I have found some code examples that work on other pages but return zero results on the blog page itself.

I tried installing the widgets extension but that broke my admin panel.

What is the correct place for the RecentPosts function.

Thanks
Toby

Avatar
Tobyc

Community Member, 2 Posts

30 June 2016 at 10:29pm

Edited: 30/06/2016 10:30pm

I solved this by adding the following 'RecentNews' function into my code/page.php file

	class Page extends SiteTree
	{
		private static $db = array();

		private static $has_one = array();
	}

	class Page_Controller extends ContentController
	{
		private static $allowed_actions = array(

			'RecentNews'
		);

		public function init()
		{
			parent::init();

		}

		function HomePage()
		{
			return HomePage::get()->limit(1)->first();
		}

		function ContactPage()
		{
			return ContactPage::get()->limit(1)->first();
		}

		public function RecentNews()
		{
			return BlogPost::get()
				->sort('PublishDate', 'DESC')
				->limit(5);
		}

	}

Then called it with the following in the BlogSideBar.ss file

<div class='blog-sidebar typography unit size1of4 lastUnit'>
	<h3>Recent News</h3>
	
<% if $RecentNews %>

	<% loop $RecentNews %>
		
		<div class='archived-article'>
			<p class='date-cat'>
				DATE $PublishDate.format('d.m.Y') /
				<span class="cat-name">
					<% if $Categories %>
						<% loop $Categories %>
							$Title
						<% end_loop %>
					<% end_if %>
				</span>
			</p>
			<h4>$Title</h4>
			<% if $Summary %>
				<p>$Summary</p>
			<% else %>
				<p>$Excerpt.FirstSentence</p>
			<% end_if %>
			<a href='$Link' class='read-more'>
				Read More
			</a>
		</div>

	<% end_loop %>

<% else %>
	
	<p>No recent articles.</p>
	
<% end_if %>

</div>

With that you will be able to put recent blog posts on any page on your site.

Hope this helps someone out.

Cheers
TobyC