You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/5.x/reference/field-types/categories.md
+89-35Lines changed: 89 additions & 35 deletions
Original file line number
Diff line number
Diff line change
@@ -78,9 +78,7 @@ Double-click on a related category to edit it in a [slideout](../../system/contr
78
78
79
79
### Querying Elements with Categories Fields
80
80
81
-
When [querying for elements](../../development/element-queries.md) that have a Categories field, you can filter the results based on the Categories field data using a query param named after your field’s handle.
82
-
83
-
Possible values include:
81
+
When [querying for elements](../../development/element-queries.md) that may have a categories field, you can use values compatible with [relational query params](../../system/relations.md) to narrow the results:
84
82
85
83
| Value | Fetches elements…
86
84
| - | -
@@ -90,44 +88,102 @@ Possible values include:
90
88
| `[100, 200]` | that are related to a category with an ID of 100 or 200.
91
89
| `[':empty:', 100, 200]` | with no related categories, or are related to a category with an ID of 100 or 200.
92
90
| `['and', 100, 200]` | that are related to the categories with IDs of 100 and 200.
93
-
| a [Category](craft5:craft\elements\Category)object | that are related to the category.
91
+
| one or more [Category](craft5:craft\elements\Category)elements | that are related to the category/categories.
94
92
| a [CategoryQuery](craft5:craft\elements\db\CategoryQuery) object | that are related to any of the resulting categories.
95
93
96
-
::: code
94
+
In general, you won’t know a specific category’s ID up-front. Here’s how you might use a category field param to fetch entries belonging to a particular category, in a blog:
95
+
97
96
```twig
98
-
{# Fetch entries with a related category #}
99
-
{% set entries = craft.entries()
100
-
.myFieldHandle(':notempty:')
97
+
{% set posts = craft.entries()
98
+
.section('posts')
99
+
.myCategoriesField(category)
101
100
.all() %}
102
101
```
103
-
```php
104
-
// Fetch entries with a related category
105
-
$entries = \craft\elements\Entry::find()
106
-
->myFieldHandle(':notempty:')
107
-
->all();
102
+
103
+
This example assumes we’re loading entries from a [category’s template](../element-types/categories.md#routing-and-templates), where the `category` variable is automatically injected. This same approach would work if we were instead looking for related content, on an individual post page:
104
+
105
+
```twig
106
+
{# Fetch IDs of the current post’s categories: #}
107
+
{% set currentPostCategories = entry.myCategoriesField.ids() %}
108
+
109
+
{# Use them in a new entries query: #}
110
+
{% set relatedPosts = craft.entries()
111
+
.section('posts')
112
+
.myCategoriesField(currentPostCategories)
113
+
.limit(5)
114
+
.all() %}
115
+
```
116
+
117
+
This query will return entries related to _any_ of the current post’s categories. Prepend `and` to the array to find entries that share _all_ their categories with the current post:
118
+
119
+
```twig
120
+
['and', ...currentPostCategories]
121
+
```
122
+
123
+
All the examples so far are achievable using generic [relational query methods](../../system/relations.md#the-relatedto-parameter), but automatically ensure that relationships are defined in a specific field, and in a specific direction (as _targets_). An equivalent query using `.relatedTo()` might look something like this:
124
+
125
+
```twig{5-8}
126
+
{% set currentPostCategories = entry.myCategoriesField.ids() %}
127
+
128
+
{% set relatedPosts = craft.entries()
129
+
.section('posts')
130
+
.relatedTo({
131
+
field: 'myCategoriesField',
132
+
targetElement: currentPostCategories,
133
+
})
134
+
.limit(5)
135
+
.all() %}
136
+
```
137
+
138
+
The last example we’ll look at uses the [special `:empty:` token](../../system/relations.md#sources-and-targets) to find post entries with _no_ categories related to the field:
139
+
140
+
```twig{3}
141
+
{% set uncategorized = craft.entries()
142
+
.section('posts')
143
+
.myCategoriesField(':empty:')
144
+
.all() %}
145
+
```
146
+
147
+
::: warning
148
+
This query may still return entries related to categories via _other_ fields! You can combine multiple category field params to better define “uncategorized:”
149
+
150
+
```twig{3-4}
151
+
{% set uncategorized = craft.entries()
152
+
.section('posts')
153
+
.topics(':empty:')
154
+
.productFamilies(':empty:')
155
+
.all() %}
156
+
157
+
{# ...or... }
158
+
159
+
{% set uncategorized = craft.entries()
160
+
.section('posts')
161
+
.relatedTo({
162
+
targetElement: ':empty:',
163
+
field: ['topics', 'productFamilies'],
164
+
})
165
+
.all() %}
108
166
```
109
167
:::
110
168
111
169
### Working with Categories Field Data
112
170
113
-
If you have an element with a Categories field in your template, you can access its related categories using your Categories field’s handle:
171
+
If you have an element with a categories field in your template, you can access the related category elements using the field’s handle:
114
172
115
173
::: code
116
174
```twig
117
-
{% set query = entry.myFieldHandle %}
175
+
{% set query = entry.myCategoriesField %}
118
176
```
119
177
```php
120
-
$query = $entry->myFieldHandle;
178
+
$query = $entry->myCategoriesField;
121
179
```
122
180
:::
123
181
124
-
That will give you a [category query](../element-types/categories.md#querying-categories), prepped to output all the related categories for the given field.
125
-
126
-
To loop through all the related categories as a flat list, call [all()](craft5:craft\db\Query::all()) and then loop over the results:
182
+
That will give you a [category query](../element-types/categories.md#querying-categories), prepped to return all the related categories for the given field. You can use the results as a list…
127
183
128
184
::: code
129
185
```twig
130
-
{% set relatedCategories = entry.myFieldHandle.all() %}
186
+
{% set relatedCategories = entry.myCategoriesField.all() %}
131
187
{% if relatedCategories|length %}
132
188
<ul>
133
189
{% for rel in relatedCategories %}
@@ -137,7 +193,7 @@ To loop through all the related categories as a flat list, call [all()](craft5:c
@@ -187,12 +243,12 @@ If you need to check for related categories without fetching them, you can call
187
243
188
244
::: code
189
245
```twig
190
-
{% if entry.myFieldHandle.exists() %}
246
+
{% if entry.myCategoriesField.exists() %}
191
247
<p>There are related categories!</p>
192
248
{% endif %}
193
249
```
194
250
```php
195
-
if ($entry->myFieldHandle->exists()) {
251
+
if ($entry->myCategoriesField->exists()) {
196
252
// do something with related categories
197
253
}
198
254
```
@@ -202,21 +258,19 @@ You can set [parameters](../element-types/categories.md#parameters) on the categ
202
258
203
259
::: code
204
260
```twig
205
-
{% set relatedCategories = entry.myFieldHandle
261
+
{% set relatedCategories = entry.myCategoriesField
206
262
.leaves()
207
263
.all() %}
208
264
```
209
265
```php
210
-
$relatedAssets = $entry->myFieldHandle
266
+
$relatedAssets = $entry->myCategoriesField
211
267
->leaves()
212
268
->all();
213
269
```
214
270
:::
215
271
216
272
::: tip
217
-
<Todonotes="Extract this into a snippet." />
218
-
219
-
In Craft 3, we recommended cloning these query objects using the [`clone` keyword](https://www.php.net/manual/en/language.oop5.cloning.php) or [`clone()`](../twig/functions.md#clone) Twig function before applying params. **This is no longer required in Craft 4**, because a new copy of the query is returned each time you access the field property.
273
+
Each time you access a category field by its handle, Craft returns a new element query.
220
274
:::
221
275
222
276
### Saving Categories Fields
@@ -228,7 +282,7 @@ For example, you could create a list of checkboxes for each of the possible rela
228
282
```twig
229
283
{# Include a hidden input first so Craft knows to update the existing value
0 commit comments