Custom function and options

Once you’ve got your head around the basics of perch_content, you can begin to explore more advanced features of custom functions.

As well as specifying a region, custom functions like perch_content_custom and perch_blog_custom allow you to pass through options. So, if you need to sort or filter your content in any way, it’s likely that you’ll want to use these.

The simplicity of custom functions is a key advantage of Perch over Wordpress. Instead of the following in WP:

<?php $cat_id = get_cat_ID('Cats'); ?>
<?php query_posts('cat_id'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <!-- HTML HERE -->  
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

Perch just has:

<?php perch_blog_custom(array(
      'category' => 'Cats'
); ?>

It’s simple, but powerful too, allowing you to easily do advanced sorting, filtering and templating while keeping your codebase easy to maintain.

Each option

One of the less well known features of perch_content_custom is the ‘each’ option. This allows users to piggyback (technical term!) functions on the back of each item returned.

Let’s imagine for example, we’re building a blog for a client and on their list of posts about Cats instead of displaying the date and time they like the idea of displaying time since the article was posted. The each option makes that simple.

Once we’ve borrowed this handy function from CSS Tricks, we can use the each function to add a new field to our item.

<?php perch_blog_custom(array(
      'category' => 'Cats'
      'each'=> function($item) {
        $item['ago'] = ago(strtotime($item['postDateTime']));
         return $item;
       }
); ?>

(In case you’re wondering strotime turns something like 2009-01-01 20:00:05 into a unix timestamp which is what Chris’ function requires)

In our template we can then suppress the postDateTime field, and display the new ‘ago’ field:

<perch:blog id="postDateTime" type="date" time="true"suppress="true"/>
<perch:blog id="ago" type="hidden" />

Keir Moffa shows another great example of the each option at work in this forum post about related content in Perch.


Leave a comment