Solutions

Homepage pulling in latest news item

19 October 2009

If you have created a news page – such as the one in this solution then you might like to display the latest news article on the homepage of your site.

Perch 1.2 introduces a new feature that enables you to do this automatically.

On your homepage or other page you want to be able to display the latest item add the following code in the position the item should display.

<?php 
$opts = array(
	'template'=>'homepage_news.html',
	'page'=>'/news.php',
	'sort'=>'date',
	'sort-order'=>'DESC',
	'count'=>1
);
perch_content_custom('News',$opts); 
?>

The perch_content_custom() tags enables you to take some of the content from elsewhere on your site and reuse it. It takes two parameters. The first – in our case ‘News’ – is the ID of the content you want to reuse and the second is an array $opts. This array contains the following information:

template – the template used to display the content on this page
page – the page that the original content is on. This needs to be a path from the root of your site so /news.php or /company/news.php etc.
sort – the field the content is to be sorted on
sort-order – ASC or DESC for ascending or descending
count – the number of entries to display

Homepage news mark-up

We also need to create a template for the content on this page if we want it to display differently than when it is displayed in the listing. I made a copy of perch/templates/article.html and removed the fields that I didn’t want included and also added a link to the news page.

<div id="homepage_news">
<h3><perch:content id="heading" type="text" label="Heading" required="true" /></h3>

<p class="date"><perch:content id="date" type="date" label="Date" format="d M Y" required="true" /></p>

<perch:content id="body" type="textarea" label="Body" textile="true" editor="markitup" required="true" />

<p><a href="news.php">Read more news</a></p>
</div>

Save your files and refresh the page in the browser, you should see the latest news item displayed. For another use of the perch_content_custom tag see my article about creating an FAQ page.

Files for this solution are available to download. Just add the template files to your perch/templates/content directory and drop the index.php and news.php into your site to try this solution for yourself.

Posted by Rachel Andrew at 15:22
Tagged: