How many times is a file using on the site/page

I like to find out if or how many time i file is used in the whole site/page. Something like that:

medias:
   type: files
   layout: cardlets
   info: {{ number of how many times that the file is in used }}

Maybe i can solve this with a site method. But than i need a walker through all fields to see where it’s used.

Here is a solution.

medias:
    type: files
    layout: cardlets
    info: "{{ site.getUsed(file) }}"
'siteMethods' => [
    'getUsed' => function($file) {
        $count = 0;
        foreach (site()->index() as $pages) {
            foreach ($pages->content()->fields() as $field) {
                $count = $count + substr_count($field->value(),$file->uuid());
            }
        }
        return $count;
    }
]

It’s dirty, cause:

  • It’s goes through every page and every field. (Slow with large sites)
  • It ignores languages, drafts and the homepage
  • If the Uuid of the image is not unique (by copying) it count multiple times.

For every single file in the section… I don’t think this is a good idea.

I know it’s a horrible idea. :see_no_evil: But what about this:

'fileMethods' => [
	'used' => function() {
		$uuid = str_replace('file://', '', $this->uuid());
		$parent = $this->parent();
		return substr_count(json_encode($parent->readContent()), $uuid);
	}
],

There’s two things left to keep in mind:

  1. It’s not for multilanguage
  2. It only work if the file is used on the same page.

And you can use it with @texnixe nice filedisplay plugin:

sections:
  medias:
    label: All Image
    type: filesdisplay
    layout: cardlets
    info: "In use: {{ file.used }}"
    query: site.files.add(site.index(true).files)

That’s definitely the better approach, for multi-language you could pass the language code to the readContent() method (then you would get the number per language), or loop through all languages to get the sum of all languages.