How to list pages and content in Perch CMS
Today, @foamcow on twitter was asking how to list snippets of pages on Perch. So I thought I would have a break and list how I did it – which may not be the best method, but it worked for me.
I had pages with perch content fields, with, for the reason of this example, we’ll call Heading a plain text field, Image (image field) and a Content (textarea).
Initially I though I was stuck, but the forums told me to list the pages I need based on the navigation functions, so in brief, here’s how I did it. Apologies for lack of syntax highlighting etc, will add that later!
<?php
// Let's get the list of pages according to the navigation first.
// Restrict to the path we need, which is only pages in /projects/
// skip-template means we just get an array of the page data back.
$navigation = perch_pages_navigation(array(
'from-path' => '/projects/',
'levels' => 1,
'skip-template' => true
));
// Now let's loop through the perch content in the project page template<br />
foreach( $navigation as $item ) {
// Add Skip template so we can use the data<br />
$opts = array(<br />
'page' => $item['pagePath'], // This is where we use the data from the nav list to get each page in turn
'skip-template' => true
);
// Now get an array of data for each perch content area in the page template
// All using the same options array we just set using the nav pagePath
$data = perch_content_custom('Heading', $opts);
$desc = perch_content_custom('Content', $opts);
$images = perch_content_custom('Image', $opts);
?>
<article>
// This bit was more complicated for me - print_r your own array to work out what array index you need.
<a href="<?php echo $item['pagePath'];?>">
<img src="/perch/resources/< ?php echo $images[0]['image']['sizes']['w684h386c1']['path']; ?>" alt="" />
</a>
<h2><a href="<?php echo $item['pagePath'];?>"><?php echo $data[0]['text']; ?></a></h2>
<p><?php echo $desc[0]['text']; ?> <a href="< ?php echo $item['pagePath'];?>">More</a>
</article>
<?php
} // foreach
?>
And hopefully that should work – but if not it has the basic theory. You can flag items by adding another suppressed field to the project page template and then checking the value in the for loop, which I have done before, although there may be a more efficient way to do that.