Dot All Lisbon – the official Craft CMS conference – is happening September 23 - 25.

Tags

You can create folksonomies for your entries, users, and assets using Tags. Tags are another type of element.

With the release of Craft 4.4, we began consolidating features of other element types into entries.

A comparable tags field UI has not yet been introduced for entries. If you or your clients value this authoring experience, it is safe to continue using tags!

As part of that process, we introduced a console command that can automate the conversion of tags to channel sections:

php craft entrify/tags myTagGroupHandle

Read more about this transition on our blog.

Tag Groups

Before you can create tags, you must create Tag Groups to contain them.

To create a new tag group, go to SettingsTags and click New Tag Group.

Each tag group holds a unique set of tags, and lets you define a custom set of fields that should be available to tags within the group. However, you don’t need to assign any fields to the Tag Group Field Layout in order to use the group.

There is no centralized editing view for tags (like there is for other element types), so fields you attach will only be editable via a slideout, after a tag has been created and assigned to a tag field.

Assigning Tags

To assign tags to things (like Entries), you must create a Tags field and add it to a Field Layout.

Each Tags field is connected to a single tag group. Whatever you attach the field to (entries, assets, users, etc.) will be able to create new tags and create relations to any of the tags within that group.

Querying Tags

You can fetch tags in your templates or PHP code using a tag query.

{# Create a new tag query #}
{% set myTagQuery = craft.tags() %}
// Create a new tag query
$myTagQuery = \craft\elements\Tag::find();

Once you’ve created a tag query, you can set parameters on it to narrow down the results, and then execute it by calling .all(). An array of Tag objects will be returned.

See Element Queries to learn about how element queries work.

Example

We can display a list of the tags in a “Blog Tags” tag group by doing the following:

  1. Create a tag query with craft.tags().
  2. Set the group parameter on it.
  3. Fetch the tags with .all().
  4. Loop through the tags using a for tag to create the list HTML.
{# Create a tag query with the 'group' parameter #}
{% set myTagQuery = craft.tags()
  .group('blogTags') %}

{# Fetch the tags #}
{% set tags = myTagQuery.all() %}

{# Display the tag list #}
  {% for tag in tags %}
    <li><a href="{{ url('blog/tags/'~tag.id) }}">{{ tag.title }}</a></li>
  {% endfor %}

Parameters

Tag queries support the following parameters:

| Param | Description | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | andNotRelatedTo | Narrows the query results to only tags that are not related to certain other elements. | andRelatedTo | Narrows the query results to only tags that are related to certain other elements. | andWith | Causes the query to return matching tags eager-loaded with related elements, in addition to the elements that were already specified by with. | asArray | Causes the query to return matching tags as arrays of data, rather than Tag objects. | cache | Enables query cache for this Query. | canonicalsOnly | Narrows the query results to only canonical elements, including elements that reference another canonical element via canonicalId so long as they aren’t a draft. | clearCachedResult | Clears the cached result. | dateCreated | Narrows the query results based on the tags’ creation dates. | dateUpdated | Narrows the query results based on the tags’ last-updated dates. | eagerly | Causes the query to be used to eager-load results for the query’s source element and any other elements in its collection. | fixedOrder | Causes the query results to be returned in the order specified by id. | getFieldLayouts | Returns the field layouts that could be associated with the resulting elements. | group | Narrows the query results based on the tag groups the tags belong to. | groupId | Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs. | id | Narrows the query results based on the tags’ IDs. | ignorePlaceholders | Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by craft\services\Elements::setPlaceholderElement(). | inBulkOp | Narrows the query results to only tags that were involved in a bulk element operation. | inReverse | Causes the query results to be returned in reverse order. | language | Determines which site(s) the tags should be queried in, based on their language. | limit | Determines the number of tags that should be returned. | notRelatedTo | Narrows the query results to only tags that are not related to certain other elements. | offset | Determines how many tags should be skipped in the results. | orderBy | Determines the order that the tags should be returned in. (If empty, defaults to title ASC.) | preferSites | If unique is set, this determines which site should be selected when querying multi-site elements. | prepForEagerLoading | Prepares the query for lazy eager loading. | prepareSubquery | Prepares the element query and returns its subquery (which determines what elements will be returned). | relatedTo | Narrows the query results to only tags that are related to certain other elements. | render | Executes the query and renders the resulting elements using their partial templates. | search | Narrows the query results to only tags that match a search query. | site | Determines which site(s) the tags should be queried in. | siteId | Determines which site(s) the tags should be queried in, per the site’s ID. | siteSettingsId | Narrows the query results based on the tags’ IDs in the elements_sites table. | title | Narrows the query results based on the tags’ titles. | trashed | Narrows the query results to only tags that have been soft-deleted. | uid | Narrows the query results based on the tags’ UIDs. | unique | Determines whether only elements with unique IDs should be returned by the query. | uri | Narrows the query results based on the tags’ URIs. | wasCountEagerLoaded | Returns whether the query result count was already eager loaded by the query's source element. | wasEagerLoaded | Returns whether the query results were already eager loaded by the query's source element. | with | Causes the query to return matching tags eager-loaded with related elements. | withCustomFields | Sets whether custom fields should be factored into the query. | withProvisionalDrafts | Causes the query to return provisional drafts for the matching elements, when they exist for the current user.

andNotRelatedTo

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that are not related to certain other elements.

See Relations for a full explanation of how to work with this parameter.

::: code

{# Fetch all tags that are related to myCategoryA and not myCategoryB #}
{% set tags = craft.tags()
  .relatedTo(myCategoryA)
  .andNotRelatedTo(myCategoryB)
  .all() %}
// Fetch all tags that are related to $myCategoryA and not $myCategoryB
$tags = \craft\elements\Tag::find()
    ->relatedTo($myCategoryA)
    ->andNotRelatedTo($myCategoryB)
    ->all();

:::

andRelatedTo

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that are related to certain other elements.

See Relations for a full explanation of how to work with this parameter.

::: code

{# Fetch all tags that are related to myCategoryA and myCategoryB #}
{% set tags = craft.tags()
  .relatedTo(myCategoryA)
  .andRelatedTo(myCategoryB)
  .all() %}
// Fetch all tags that are related to $myCategoryA and $myCategoryB
$tags = \craft\elements\Tag::find()
    ->relatedTo($myCategoryA)
    ->andRelatedTo($myCategoryB)
    ->all();

:::

andWith

Defined by craft\elements\db\ElementQuery

Causes the query to return matching tags eager-loaded with related elements, in addition to the elements that were already specified by with.

.

asArray

Defined by craft\elements\db\ElementQuery

Causes the query to return matching tags as arrays of data, rather than Tag objects.

::: code

{# Fetch tags as arrays #}
{% set tags = craft.tags()
  .asArray()
  .all() %}
// Fetch tags as arrays
$tags = \craft\elements\Tag::find()
    ->asArray()
    ->all();

:::

cache

Defined by craft\elements\db\ElementQuery

Enables query cache for this Query.

canonicalsOnly

Defined by craft\elements\db\ElementQuery

Narrows the query results to only canonical elements, including elements that reference another canonical element via canonicalId so long as they aren’t a draft.

Unpublished drafts can be included as well if drafts(null) and draftOf(false) are also passed.

clearCachedResult

Defined by craft\elements\db\ElementQuery

Clears the cached result.

dateCreated

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ creation dates.

Possible values include:

| Value | Fetches tags… | - | - | '>= 2018-04-01' | that were created on or after 2018-04-01. | '< 2018-05-01' | that were created before 2018-05-01. | ['and', '>= 2018-04-04', '< 2018-05-01'] | that were created between 2018-04-01 and 2018-05-01. | now/today/tomorrow/yesterday | that were created at midnight of the specified relative date.

::: code

{# Fetch tags created last month #}
{% set start = date('first day of last month')|atom %}
{% set end = date('first day of this month')|atom %}

{% set tags = craft.tags()
  .dateCreated(['and', ">= #{start}", "< #{end}"])
  .all() %}
// Fetch tags created last month
$start = (new \DateTime('first day of last month'))->format(\DateTime::ATOM);
$end = (new \DateTime('first day of this month'))->format(\DateTime::ATOM);

$tags = \craft\elements\Tag::find()
    ->dateCreated(['and', ">= {$start}", "< {$end}"])
    ->all();

:::

dateUpdated

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ last-updated dates.

Possible values include:

| Value | Fetches tags… | - | - | '>= 2018-04-01' | that were updated on or after 2018-04-01. | '< 2018-05-01' | that were updated before 2018-05-01. | ['and', '>= 2018-04-04', '< 2018-05-01'] | that were updated between 2018-04-01 and 2018-05-01. | now/today/tomorrow/yesterday | that were updated at midnight of the specified relative date.

::: code

{# Fetch tags updated in the last week #}
{% set lastWeek = date('1 week ago')|atom %}

{% set tags = craft.tags()
  .dateUpdated(">= #{lastWeek}")
  .all() %}
// Fetch tags updated in the last week
$lastWeek = (new \DateTime('1 week ago'))->format(\DateTime::ATOM);

$tags = \craft\elements\Tag::find()
    ->dateUpdated(">= {$lastWeek}")
    ->all();

:::

eagerly

Defined by craft\elements\db\ElementQuery

Causes the query to be used to eager-load results for the query’s source element and any other elements in its collection.

fixedOrder

Defined by craft\elements\db\ElementQuery

Causes the query results to be returned in the order specified by id.

::: tip If no IDs were passed to id, setting this to true will result in an empty result set. :::

::: code

{# Fetch tags in a specific order #}
{% set tags = craft.tags()
  .id([1, 2, 3, 4, 5])
  .fixedOrder()
  .all() %}
// Fetch tags in a specific order
$tags = \craft\elements\Tag::find()
    ->id([1, 2, 3, 4, 5])
    ->fixedOrder()
    ->all();

:::

getFieldLayouts

Defined by craft\elements\db\ElementQuery

Returns the field layouts that could be associated with the resulting elements.

group

Narrows the query results based on the tag groups the tags belong to.

Possible values include:

| Value | Fetches tags… | - | - | 'foo' | in a group with a handle of foo. | 'not foo' | not in a group with a handle of foo. | ['foo', 'bar'] | in a group with a handle of foo or bar. | ['not', 'foo', 'bar'] | not in a group with a handle of foo or bar. | a TagGroup object | in a group represented by the object.

::: code

{# Fetch tags in the Foo group #}
{% set tags = craft.tags()
  .group('foo')
  .all() %}
// Fetch tags in the Foo group
$tags = \craft\elements\Tag::find()
    ->group('foo')
    ->all();

:::

groupId

Narrows the query results based on the tag groups the tags belong to, per the groups’ IDs.

Possible values include:

| Value | Fetches tags… | - | - | 1 | in a group with an ID of 1. | 'not 1' | not in a group with an ID of 1. | [1, 2] | in a group with an ID of 1 or 2. | ['not', 1, 2] | not in a group with an ID of 1 or 2.

::: code

{# Fetch tags in the group with an ID of 1 #}
{% set tags = craft.tags()
  .groupId(1)
  .all() %}
// Fetch tags in the group with an ID of 1
$tags = \craft\elements\Tag::find()
    ->groupId(1)
    ->all();

:::

id

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ IDs.

Possible values include:

| Value | Fetches tags… | - | - | 1 | with an ID of 1. | 'not 1' | not with an ID of 1. | [1, 2] | with an ID of 1 or 2. | ['not', 1, 2] | not with an ID of 1 or 2.

::: code

{# Fetch the tag by its ID #}
{% set tag = craft.tags()
  .id(1)
  .one() %}
// Fetch the tag by its ID
$tag = \craft\elements\Tag::find()
    ->id(1)
    ->one();

:::

::: tip This can be combined with fixedOrder if you want the results to be returned in a specific order. :::

ignorePlaceholders

Defined by craft\elements\db\ElementQuery

Causes the query to return matching tags as they are stored in the database, ignoring matching placeholder elements that were set by craft\services\Elements::setPlaceholderElement().

inBulkOp

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that were involved in a bulk element operation.

inReverse

Defined by craft\elements\db\ElementQuery

Causes the query results to be returned in reverse order.

::: code

{# Fetch tags in reverse #}
{% set tags = craft.tags()
  .inReverse()
  .all() %}
// Fetch tags in reverse
$tags = \craft\elements\Tag::find()
    ->inReverse()
    ->all();

:::

language

Defined by craft\elements\db\ElementQuery

Determines which site(s) the tags should be queried in, based on their language.

Possible values include:

| Value | Fetches tags… | - | - | 'en' | from sites with a language of en. | ['en-GB', 'en-US'] | from sites with a language of en-GB or en-US. | ['not', 'en-GB', 'en-US'] | not in sites with a language of en-GB or en-US.

::: tip Elements that belong to multiple sites will be returned multiple times by default. If you only want unique elements to be returned, use unique in conjunction with this. :::

::: code

{# Fetch tags from English sites #}
{% set tags = craft.tags()
  .language('en')
  .all() %}
// Fetch tags from English sites
$tags = \craft\elements\Tag::find()
    ->language('en')
    ->all();

:::

limit

Defined by yii\db\QueryTrait

Determines the number of tags that should be returned.

::: code

{# Fetch up to 10 tags  #}
{% set tags = craft.tags()
  .limit(10)
  .all() %}
// Fetch up to 10 tags
$tags = \craft\elements\Tag::find()
    ->limit(10)
    ->all();

:::

notRelatedTo

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that are not related to certain other elements.

See Relations for a full explanation of how to work with this parameter.

::: code

{# Fetch all tags that are related to myEntry #}
{% set tags = craft.tags()
  .notRelatedTo(myEntry)
  .all() %}
// Fetch all tags that are related to $myEntry
$tags = \craft\elements\Tag::find()
    ->notRelatedTo($myEntry)
    ->all();

:::

offset

Defined by yii\db\QueryTrait

Determines how many tags should be skipped in the results.

::: code

{# Fetch all tags except for the first 3 #}
{% set tags = craft.tags()
  .offset(3)
  .all() %}
// Fetch all tags except for the first 3
$tags = \craft\elements\Tag::find()
    ->offset(3)
    ->all();

:::

orderBy

Defined by craft\elements\db\ElementQuery

Determines the order that the tags should be returned in. (If empty, defaults to title ASC.)

::: code

{# Fetch all tags in order of date created #}
{% set tags = craft.tags()
  .orderBy('dateCreated ASC')
  .all() %}
// Fetch all tags in order of date created
$tags = \craft\elements\Tag::find()
    ->orderBy('dateCreated ASC')
    ->all();

:::

preferSites

Defined by craft\elements\db\ElementQuery

If unique is set, this determines which site should be selected when querying multi-site elements.

For example, if element “Foo” exists in Site A and Site B, and element “Bar” exists in Site B and Site C, and this is set to ['c', 'b', 'a'], then Foo will be returned for Site B, and Bar will be returned for Site C.

If this isn’t set, then preference goes to the current site.

::: code

{# Fetch unique tags from Site A, or Site B if they don’t exist in Site A #}
{% set tags = craft.tags()
  .site('*')
  .unique()
  .preferSites(['a', 'b'])
  .all() %}
// Fetch unique tags from Site A, or Site B if they don’t exist in Site A
$tags = \craft\elements\Tag::find()
    ->site('*')
    ->unique()
    ->preferSites(['a', 'b'])
    ->all();

:::

prepForEagerLoading

Defined by craft\elements\db\ElementQuery

Prepares the query for lazy eager loading.

prepareSubquery

Defined by craft\elements\db\ElementQuery

Prepares the element query and returns its subquery (which determines what elements will be returned).

relatedTo

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that are related to certain other elements.

See Relations for a full explanation of how to work with this parameter.

::: code

{# Fetch all tags that are related to myCategory #}
{% set tags = craft.tags()
  .relatedTo(myCategory)
  .all() %}
// Fetch all tags that are related to $myCategory
$tags = \craft\elements\Tag::find()
    ->relatedTo($myCategory)
    ->all();

:::

render

Defined by craft\elements\db\ElementQuery

Executes the query and renders the resulting elements using their partial templates.

If no partial template exists for an element, its string representation will be output instead.

search

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that match a search query.

See Searching for a full explanation of how to work with this parameter.

::: code

{# Get the search query from the 'q' query string param #}
{% set searchQuery = craft.app.request.getQueryParam('q') %}

{# Fetch all tags that match the search query #}
{% set tags = craft.tags()
  .search(searchQuery)
  .all() %}
// Get the search query from the 'q' query string param
$searchQuery = \Craft::$app->request->getQueryParam('q');

// Fetch all tags that match the search query
$tags = \craft\elements\Tag::find()
    ->search($searchQuery)
    ->all();

:::

site

Defined by craft\elements\db\ElementQuery

Determines which site(s) the tags should be queried in.

The current site will be used by default.

Possible values include:

| Value | Fetches tags… | - | - | 'foo' | from the site with a handle of foo. | ['foo', 'bar'] | from a site with a handle of foo or bar. | ['not', 'foo', 'bar'] | not in a site with a handle of foo or bar. | a craft\models\Site object | from the site represented by the object. | '*' | from any site.

::: tip If multiple sites are specified, elements that belong to multiple sites will be returned multiple times. If you only want unique elements to be returned, use unique in conjunction with this. :::

::: code

{# Fetch tags from the Foo site #}
{% set tags = craft.tags()
  .site('foo')
  .all() %}
// Fetch tags from the Foo site
$tags = \craft\elements\Tag::find()
    ->site('foo')
    ->all();

:::

siteId

Defined by craft\elements\db\ElementQuery

Determines which site(s) the tags should be queried in, per the site’s ID.

The current site will be used by default.

Possible values include:

| Value | Fetches tags… | - | - | 1 | from the site with an ID of 1. | [1, 2] | from a site with an ID of 1 or 2. | ['not', 1, 2] | not in a site with an ID of 1 or 2. | '*' | from any site.

::: code

{# Fetch tags from the site with an ID of 1 #}
{% set tags = craft.tags()
  .siteId(1)
  .all() %}
// Fetch tags from the site with an ID of 1
$tags = \craft\elements\Tag::find()
    ->siteId(1)
    ->all();

:::

siteSettingsId

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ IDs in the elements_sites table.

Possible values include:

| Value | Fetches tags… | - | - | 1 | with an elements_sites ID of 1. | 'not 1' | not with an elements_sites ID of 1. | [1, 2] | with an elements_sites ID of 1 or 2. | ['not', 1, 2] | not with an elements_sites ID of 1 or 2.

::: code

{# Fetch the tag by its ID in the elements_sites table #}
{% set tag = craft.tags()
  .siteSettingsId(1)
  .one() %}
// Fetch the tag by its ID in the elements_sites table
$tag = \craft\elements\Tag::find()
    ->siteSettingsId(1)
    ->one();

:::

title

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ titles.

Possible values include:

| Value | Fetches tags… | - | - | 'Foo' | with a title of Foo. | 'Foo*' | with a title that begins with Foo. | '*Foo' | with a title that ends with Foo. | '*Foo*' | with a title that contains Foo. | 'not *Foo*' | with a title that doesn’t contain Foo. | ['*Foo*', '*Bar*'] | with a title that contains Foo or Bar. | ['not', '*Foo*', '*Bar*'] | with a title that doesn’t contain Foo or Bar.

::: code

{# Fetch tags with a title that contains "Foo" #}
{% set tags = craft.tags()
  .title('*Foo*')
  .all() %}
// Fetch tags with a title that contains "Foo"
$tags = \craft\elements\Tag::find()
    ->title('*Foo*')
    ->all();

:::

trashed

Defined by craft\elements\db\ElementQuery

Narrows the query results to only tags that have been soft-deleted.

::: code

{# Fetch trashed tags #}
{% set tags = craft.tags()
  .trashed()
  .all() %}
// Fetch trashed tags
$tags = \craft\elements\Tag::find()
    ->trashed()
    ->all();

:::

uid

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ UIDs.

::: code

{# Fetch the tag by its UID #}
{% set tag = craft.tags()
  .uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
  .one() %}
// Fetch the tag by its UID
$tag = \craft\elements\Tag::find()
    ->uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
    ->one();

:::

unique

Defined by craft\elements\db\ElementQuery

Determines whether only elements with unique IDs should be returned by the query.

This should be used when querying elements from multiple sites at the same time, if “duplicate” results is not desired.

::: code

{# Fetch unique tags across all sites #}
{% set tags = craft.tags()
  .site('*')
  .unique()
  .all() %}
// Fetch unique tags across all sites
$tags = \craft\elements\Tag::find()
    ->site('*')
    ->unique()
    ->all();

:::

uri

Defined by craft\elements\db\ElementQuery

Narrows the query results based on the tags’ URIs.

Possible values include:

| Value | Fetches tags… | - | - | 'foo' | with a URI of foo. | 'foo*' | with a URI that begins with foo. | '*foo' | with a URI that ends with foo. | '*foo*' | with a URI that contains foo. | 'not *foo*' | with a URI that doesn’t contain foo. | ['*foo*', '*bar*'] | with a URI that contains foo or bar. | ['not', '*foo*', '*bar*'] | with a URI that doesn’t contain foo or bar.

::: code

{# Get the requested URI #}
{% set requestedUri = craft.app.request.getPathInfo() %}

{# Fetch the tag with that URI #}
{% set tag = craft.tags()
  .uri(requestedUri|literal)
  .one() %}
// Get the requested URI
$requestedUri = \Craft::$app->request->getPathInfo();

// Fetch the tag with that URI
$tag = \craft\elements\Tag::find()
    ->uri(\craft\helpers\Db::escapeParam($requestedUri))
    ->one();

:::

wasCountEagerLoaded

Defined by craft\elements\db\ElementQuery

Returns whether the query result count was already eager loaded by the query's source element.

wasEagerLoaded

Defined by craft\elements\db\ElementQuery

Returns whether the query results were already eager loaded by the query's source element.

with

Defined by craft\elements\db\ElementQuery

Causes the query to return matching tags eager-loaded with related elements.

See Eager-Loading Elements for a full explanation of how to work with this parameter.

::: code

{# Fetch tags eager-loaded with the "Related" field’s relations #}
{% set tags = craft.tags()
  .with(['related'])
  .all() %}
// Fetch tags eager-loaded with the "Related" field’s relations
$tags = \craft\elements\Tag::find()
    ->with(['related'])
    ->all();

:::

withCustomFields

Defined by craft\elements\db\ElementQuery

Sets whether custom fields should be factored into the query.

withProvisionalDrafts

Defined by craft\elements\db\ElementQuery

Causes the query to return provisional drafts for the matching elements, when they exist for the current user.