Template Report

A quick and easy report Snippet to show you a count of published and unpublished Resources that use each of your Templates.

By Bob Ray  |  October 24, 2023  |  2 min read
Template Report

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 */

/* Make it run in either MODX 2 or MODX 3 */
$prefix = $modx->getVersionData()['version'] >= 3
  ? 'MODX\Revolution\\'
  : '';

$templates = $modx->getCollection($prefix . 'modTemplate');
$output = '### Template Report';
$output .= "\n";

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

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

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

        ";
        $output .= "\n";
}
$output .= "\n";

return $output;

How It Works

The strategy here is fairly simple. First, we get all the site’s Templates (after setting the prefix). It’s wasteful to retrieve all fields of every Template object just to get its ID, 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 direct access to their pagetitles. We’ll consider that case my next article.


Bob Ray is the author of the MODX: The Official Guide and dozens of MODX Extras including QuickEmail, NewsPublisher, SiteCheck, GoRevo, Personalize, EZfaq, MyComponent and many more. His website is Bob’s Guides. It not only includes a plethora of MODX tutorials but there are some really great bread recipes there, as well.