Page count — updated

| Tagged: code, snippets, tips.

In the previous post, I came up with a technique for counting published (non-hidden) pages. Here’s a slightly more elaborate version of the code for use in a snippet (as described in the previous post) which can be adjusted to include or exclude “hidden” pages:

function page_count($parent)
// recursively count all PUBLISHED pages
{
    // to OMIT hidden pages (and their children), leave $inc_hidden variable empty;
    // to INCLUDE hidden pages (and their children), change "''" in next line to "'true'":
    $inc_hidden = '';
    $i = 0;
    $childs = $parent->children(null,array(),$inc_hidden);
    if (count($childs) > 0)
    {
        $i = count($childs);
        foreach ($childs as $child) 
            $i += page_count($child);
    }
   return $i;
}
// "find('/')" tells function to count from root page
// but change '/' to count only a given branch of the site
// e.g. "find('music')" to count only the pages under the "Music" page
echo page_count($this->find('/')) + 1; // add in root page to total

At the end, there’s also a little bit of explanation for starting the page count at a different point that the root page.

It got me thinking, though, that it would enhance flexibility of snippets if these two adjustments could be passed to the snippet as parameters, rather than “hard-coding” them in the snippet itself. That would make it possible to call the same snippet from different pages in the site, for example. Something like this would do the trick:

$this->includeSnippet('snippetName', $params(put,params,here));

My knowledge of PHP is too limited to work out how best to do that, but it might be worth investigating.

This page last updated: Sat, 3 Aug 2013.

If you wish to help out Wolf CMS financially, please use our PayPal button, or consider making weekly, recurring contributions through our Gittip.com account.
Thank you!

Tags