I'm trying to write a plugin that fetches the list of files containing a particular tag (like "#condition") in ObsidianMD for some downstream purposes. The built-in global-search
can do this already, and it seems like the metadataCache
has some information about tags.
Further, the API appears to be able to getAllTags
: https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts#L1291, but I don't see any method that takes a tag and spits out a list of related files.
Does anyone know anything?
You can use app.vault.getMarkdownFiles()
to get all markdown files in the current vault, then use getAllTags()
on each file to filter those files which contain the tag. Example:
const tag = "#obsidian";
const cache = this.app.metadataCache;
const files = this.app.vault.getMarkdownFiles();
const files_with_tag = [] as TFile [];
files.forEach( (file) => {
const file_cache = cache.getFileCache(file);
const tags = getAllTags(file_cache);
if (tags.includes(tag)) {
files_with_tag.push(file);
}
});
console.log(files_with_tag);