Updating file metadata, and particularly the template that is stored for a file, is a task that comes up ever so often. Because you forgot to assign a file template in the first place or because you later changed your mind and want to assign a different template to some file types or whatever.
Since the file template assigned to a file is stored in the file metadata file (i.e. the text file that is created for each uploaded file), this is what we have to update when we want to newly assign or change the file template or any other metadata.
The method we need to update a file’s metadata is
$file->update(), so the basic code to update all files of a page looks like this (assuming for the moment that we are using this code in a page template or controller):
$file->update() requires authentication.
However, we can improve this code to get an array of error messages in case updating fails for any of the files:
The above script will only update the default language metadata if you have a multi-language site. If we want to update all languages, we need to loop through the languages for each file and pass the language code as second parameter to the
For a one-off update of a bunch of files the above code in a template will do fine. If we want to prepared to do this more often, a files method would come in handy, wouldn't it?
In a plugin, lets create a new files method that takes a data array as argument and then does the same as the code above.
We can then call this method on a collection of files anywhere like this:
Of course, you can filter your files collection by extension, type, parent or whatever other criteria might apply to your use case.