Taxonomies in Statamic provide the ability to categorize and organize content. For example, they can be used for tags, categories, or any other type of groupable content.
This code example reads all taxonomies in Statamic and prints their titles.
use Statamic\Facades\Taxonomy;
$taxonomies = Taxonomy::all();
foreach($taxonomies as $taxonomy) {
echo $taxonomy->title . PHP_EOL;
}
This code example fetches a specific taxonomy by its handle (a unique identifier) and prints its title.
use Statamic\Facades\Taxonomy;
$taxonomy = Taxonomy::findByHandle('tags');
echo $taxonomy->title . PHP_EOL;
This code example retrieves the handles of all taxonomies and prints them.
use Statamic\Facades\Taxonomy;
$handles = Taxonomy::handles();
foreach($handles as $handle) {
echo $handle . PHP_EOL;
}
Terms are the individual entries within a taxonomy. They represent the actual categorizable data.
This code example reads all terms from all taxonomies and prints their titles.
use Statamic\Facades\Term;
$terms = Term::all();
foreach($terms as $term) {
echo $term->title . PHP_EOL;
}
This code example reads all terms from a specific taxonomy (in this case "tags") and prints their titles.
use Statamic\Facades\Term;
$terms = Term::query()->where('taxonomy', 'tags')->get();
foreach($terms as $term) {
echo $term->title . PHP_EOL;
}
This code example reads all terms used in a certain collection (here "posts") and a specific taxonomy (here "tags"), then prints the titles of the terms.
use Statamic\Facades\Term;
$terms = Term::query()->where('taxonomy', 'tags')->where('collection', 'posts')->get();
foreach($terms as $term) {
echo $term->title . PHP_EOL;
}
This code example reads all terms of a specific taxonomy (here "tags") that are used in at least one entry.
use Statamic\Facades\Term;
$terms = Term::query()->where('taxonomy', 'tags')->where('entries_count', '>=', 1)->get();
foreach($terms as $term) {
echo $term->title . PHP_EOL;
}
This code example reads all terms of a specific taxonomy (here "tags") that are not used in any entries.
use Statamic\Facades\Term;
$terms = Term::query()->where('taxonomy', 'tags')->where('entries_count', '=', 0)->get();
foreach($terms as $term) {
echo $term->title . PHP_EOL;
}
The following code example queries a user and creates a taxonomy term of type "tag" in the taxonomy "tags", which is assigned to this user.
use Statamic\Facades\Term;
use Statamic\Facades\User;
$user = User::query()->where('name', 'Sebastian Widmann')->first();
$user_id = $user->id;
$term_data = [
'title' => 'My Term',
'author' => $user_id,
'updated_by'=> $user_id,
'updated_at' => time(),
'blueprint' => 'tag',
];
$term = Term::make()->taxonomy('tags')->slug('my-term');
$term->dataForLocale('default', $term_data);
$term->save();