Creating the Frontmatter Property
This wasn’t too hard. Of course, I wanted to be efficient about this process too.
To be clear, here’s the goal: “Create a way of adding a frontmatter property item called word count and have it actually produce the word count and also add/update itself for each note in the vault.”
To ensure I didn’t fuck myself, I started off with a sandbox vault (which has plenty of files in it).
Step One
First, we need to download the ‘Templater’ app (which you can find easily among the community plugins).
Once we’ve installed the Templater app, we can actually exit out of the settings panel entirely.
Step Two
Now we need to create a new file. You can name this file anything (just remember the name of the file when you enter it).
In that file, you’re going to want to copy.paste the following template code inside of it:
<%*
const files = app.vault.getMarkdownFiles();
let updatedCount = 0;
for (const file of files) {
// Skip template files if you want
if (file.path.includes("Templates/")) continue;
const content = await app.vault.read(file);
// Remove frontmatter from word count
const bodyContent = content.replace(/^---[\s\S]*?---\s*/, '').trim();
const wordCount = bodyContent ? bodyContent.split(/\s+/).length : 0;
// Update the frontmatter
await app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter.word_count = wordCount;
});
updatedCount++;
}
new Notice(`Updated ${updatedCount} notes with word counts!`);
%>
If you’re going to copy/paste this, it may be wise to select the option “paste as plain text”. Maybe you won’t have to do this. Just make sure that when you do enter this in the file that the syntax coloring renders in the same way you see it rendered in the screenshot below.
Step Three
Now, we’re going to click on the Templater icon, which should be located in your Obsidian side-ribbon.
From here, we’re going to see the option for us to search for a proper “template” file to use. Keep in mind that the script that I provided above is going to add this frontmatter to every single note in the Vault. If this is okay, with you, then select the note where you pasted the Template code that I gave in the previous step.
For me, the name of that note is New Template File.
Once you do that, then voila! This frontmatter property should be added to all of your notes.
Awesome.
Once again, Obsidian forums doesn’t allow me to add more than 5 fucking media files per post, so I gotta break this up into another fucking post.