Template Report

A snippet that will create a report giving the number of pages that use each template, with separate data on published and unpublished resources.


A MODX Forums user asked for a way to find out which of his many templates were actually in use. Here's a snippet that will create a report giving the number of pages that use each template, with separate data on published and unpublished resources.


The Code

Put this tag on a page where you'd like to see the report:

[[!TemplateReport]]


Paste this code into a snippet called TemplateReport.

/* TemplateReport snippet */
$templates = $modx->getCollection('modTemplate');

$output = '<h3>Template Report</h3>';
$output .= "\n<ul>";

foreach ($templates as $template) {
    $id = $template->get('id');
    $name = $template->get('templatename');
    $c1 = $modx->newQuery('modResource');
    $c1->where(array(
       'published' => '1',
        'template' => $id,
    ));
    $numPublished = $modx->getCount('modResource', $c1);

    $c2 = $modx->newQuery('modResource');
    $c2->where(array(
        'published' => '0',
        'template' => $id,
    ));
    $numUnpublished = $modx->getCount('modResource', $c2);

    $output .= "\n" . '<li><b>' . $name . '</b>';
        $output .= "\n
        <ul>";
            $output .= "\n" . ' <li>Published resources: ' . $numPublished . '</li>';
            $output .= "\n" . ' <li>Unpublished resources: ' . $numUnpublished . '</li>';
            $output .= "\n
        </ul>
        ";
        $output .= "\n</li>";
}
$output .= "\n</ul>";

return $output;

How it Works

The strategy here is fairly simple. First, we get all the site's templates in line 2. It's wasteful to retrieve the entire template objects just to get Their IDs, but this snippet isn't going to run very often so it's not worth the trouble to optimize it.

Next, we create two queries, one that selects the published resources, and another that selects the unpublished resources. Then, we use $modx->getCount() to get the number of resources that fit each case and report the results.


More Detail

This snippet will only report the count of published and unpublished pages using each template. You might want a list of the resources as well, but that would require a different strategy. Since we're not looping through the resources in this snippet, we have no access to their pagetitles. We'll consider that case in another article.



Comments (0)


Please login to comment.

  (Login)