Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Blog headlines on the SilverStripe HomePage

Insert your blog headlines and excerpts from the SilverStripe Blog Module into the front page of a SilverStripe website.

The SilverStripe content management system comes with a blog module which enables blog-like functionality. Unfortunately there’s no easy way to include blog headlines (or other blog content) on the HomePage. Given that most websites which contain blogs tend to feature their latest stories on the front page, this is quite a problem.

Presented below is some simple code that can be used to include blog headlines and summaries in SilverStripe.

Before you begin

These instructions assume that the front page of the website (called HomePage) has a separate controller to permit a different appearance from the rest of the site. If not, instructions can be found here.

Instructions

Step 1: Edit HomePage.php

Go to /mysite/code/HomePage.php and insert the following code:

<?php
class HomePage extends Page {
}
class HomePage_Controller extends Page_Controller {
	//This function inserts the latest blog posts
	function latestBlog(){
	$blog = DataObject::get("BlogEntry", "", "Date DESC", "", 2);
	return $blog;	
	}
}

The HomePage_Controller class has a latestBlog function nested inside. In this instance, two blog posts will be displayed. This can be changed easily by amending the number at the end of the second last line of code.

Step 2: Edit HomePage.ss

Go to /themes/(ThemeName)/templates/Layout/HomePage.ss and insert the following code:

<% if latestBlog %>
<% loop latestBlog %>
<% if Last %>
<% end_if %>

<div>
<h3><a href="$Link">$Title</a></h3>
<p>Posted: $Date.Long</p>
<p>$Content.LimitWordCount(45) <a href="$Link">Read more</a></p>
</div>
<% end_loop %>
<% else %>
<p>There are currently no blog entries to display.</p>
<% end_if %>

The above example includes only basic formatting. Insert div, span, p or other elements as desired.

Because the SilverStripe CMS blog module does not have excerpts (like WordPress, for instance), I have chosen to use the LimitWordCount() function to summarise each blog post to the first 45 words published in the story. Be aware that any HTML (including links) in those first 45 words get stripped out badly.

Step 3: Refresh!

Go to your browser and re-render templates via http://www.yourwebsite.com/dev/build/flush=1 then confirm whether the blog posts have been included in the home page as expected.

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.