Taxonomy

Introduction

Taxonomy allows for classifying your post types in groups. The names for the different groupings in a taxonomy are called terms.

Creating taxonomy

By default, taxonomies are stored inside app\Taxonomies directory.

Via console command

Scaffold taxonomy with wp assely:make taxonomy command.

wp assely:make taxonomy Genres
Specifying slug

This will create a taxonomy with genres slug, but you can specify it with --slug option.

wp assely:make taxonomy Genres --slug="genre"
Specifying owners

You can also define to which post type this taxonomy belongs to. Enter it's classname to the --belongsto option.

wp assely:make taxonomy Genres --belongsto="App\Posttypes\Movies"

Manually created class file

Make a file with the class that extends base Assely\Taxonomy\Taxonomy class.

The slug property is required. This value determines under which name your taxonomy will be registered and accessible.

// app/Taxonomies/Genres.php

namespace App\Taxonomies;

use Assely\Taxonomy\Taxonomy;

class Genres extends Taxonomy
{
    /**
     * Taxonomy slug.
     *
     * @var string
     */
    public $slug = 'genres';

    /**
     * Describe taxonomy relationships.
     *
     * @return self
     */
    public function relation()
    {
        return $this->belongsTo([
            'App\Posttypes\Movies',
            'App\Posttypes\Books',
        ]);
    }

    /**
     * Taxonomy arguments.
     *
     * @return array
     */
    public function arguments()
    {
        return [
            //
        ];
    }

    /**
     * Register taxonomy custom fields.
     *
     * @return \Assely\Field\Field[]
     */
    public function fields()
    {
        return [
            //
        ];
    }

    /**
     * Specify columns of the taxonomy terms list.
     *
     * @return \Assely\Column\Column[]
     */
    public function columns()
    {
        return [
            //
        ];
    }
}

Configuring taxonomy

Registering taxonomy

All taxonomies are registered in the config/app.php configuration file. This file contains a taxonomies array where you can add your newly created custom taxonomies.

'taxonomies' => [
    // ...other taxonomies

    App\Taxonomies\Genres::class,
],

The Arguments method

The arguments method must always return an array of taxonomy registration parameters. You can use all of the default WordPress parameters, but there is also some "assely-specific".

public function arguments()
{
    return [
        'title' => ['Grene', 'Grenes'],
        'description' => 'Movies grenes',
    ];
}
Parameter name Default value Description
title [] Array of titles, where first element is singular variant, second a plural
description '' Description text displayed above all fields.
preserve 'single' How metabox preserves his metadata.

The Relation method

Taxonomies must belong to one or multiple post types. The relation method allows you to describe where taxonomy should be assigned. Use belongsTo method with an array of post types class names as the parameter.

public function relation()
{
    return $this->belongsTo([
        'App\Posttypes\Movies',
        'App\Posttypes\Books',
    ]);
}

The Fields method

The fields method allows for listing custom fields which will be managed by the term.

use Field;

public function fields()
{
    return [
        Field::colorpicker('color')
    ];
}

The Columns method

The columns method allows for defining custom taxonomy columns which are displayed on the list of terms.

Taxonomies accept one kind of column: term.

public function columns()
{
    return [
        Column::term('App\Taxonomies\Genres', 'color'),
    ];
}

Using taxonomy

Injecting the taxonomy repository provides fluent access to its terms. However, you can also use Term facade.

Term::type('genres')->find(1);

Quering terms

Of course, once you created and registered your taxonomy, you can start retrieving terms for your views. In this section, you will learn how you can query your custom taxonomies.

Fetching multiple terms

The all method will retrieve all of the taxonomy terms. This method returns an instance of Illuminate\Support\Collection, so you can easily modify results with diffrent methods.

use App\Taxonomies\Genres;

public function index(Genres $genres) {
    view('index', [
        'genres' => $genres->all(),
    ]);
}

Retrieving single post

You can also immediately search for a single term. Pass term id as the find method argument.

use App\Taxonomies\Genres;

public function index(Genres $genres) {
    view('show', [
        'genre' => $genres->find(1),
    ]);
}
Not Found Query Exception

Sometimes you want to throw an exception when a term was not found. The findOrFail method returns the found term, but if not Assely\Database\QueryException will be thrown.

$genres->findOrFail(1);

Custom query

Needs something more complex? You can use query method with an array of parameters as the argument.

use App\Taxonomies\Genres;

public function index(Genres $genres) {
    view('index', [

        'mostUsedTerms' => $genres->query([
            'orderby' => 'count'
        ]),

    ]);
}

Inserting terms

Use create method with an array of properties and values for inserting new post to the database.

use App\Taxonomies\Genres;

public function index(Genres $movies) {
    $movies->create([
        'title' => 'Really scary horrors',
    ]);
}
Inserting Query Exception

The createdOrFail method will insert new genre, but when an error occurs Assely\Database\QueryException will be thrown.

$genres->createOrFail([
    'title' => 'Really scary horrors',
]);

Updating terms

To update a term, you need to set new property values on retrieved Assely\Adapter\Term instance, and then call save method.

use App\Taxonomies\Genres;

public function index(Genres $genres) {
    $genre = $genres->find(1);

    $genre->title = 'Really scary horrors';

    $genre->save();
}

Deleting terms

Call destroy method on retrieved Assely\Adapter\Term instance to remove a term from the database.

use App\Taxonomies\Genres;

public function index(Genres $genres) {
    $genre = $genres->find(1);

    $genre->destroy();
}

Rendering terms in templates

You have access to the bunch of different properties. List of all you can find in adapters documentation.

<div class="genre">
    {{ $genre->title }} <span>{{ $genre->count }}</span>
</div>

Looping on terms collection

Easy as pie. Just standard loop.

@foreach($genres->all() as $genre)
    <a href="{{ $genre->link }}">{{ $genre->title }}</a>
@endforeach

Accessing term metadata

Your terms may hold various metadata. The meta method helps you retrieve these information. You only need to pass metadata key under which they are stored.

{{ $genre->meta('color') }}

Retrieving term posts

To retrieve the posts with a specific term, you can use posts method with taxonomy slug as the argument.

@foreach($genres->all() as $genre)
    @foreach($genre->posts('movies') as $post)
        <h1>{{ $post->title }}</h1>
    @endforeach
@endforeach