Entries
Entries are flexible content containers that—unlike addresses, assets, or categories—have no primary or implied function. They are entirely agnostic building blocks, used to model whatever kind of content or data your project needs.
All entries support some key features like Authors, a Post Date and Expiration Date, Statuses, and content defined via field layouts. Additional features and properties are determined via entry types, or the sections and Matrix fields they’re used in.
Authors can use the drafts and revisions system to stage different versions of content and preview it before going live.
# Entry Types
Craft uses entry types to define atomic units of content, which are then exposed to editors via sections and Matrix fields.
Entry types became a global resource in Craft 5. This means you can define a content type once, then use it in multiple sections, as a nested block in a Matrix field, or some combination of the two. As a result, some settings have moved around!
Most importantly, you’ll manage entry types in the Settings → Entry Types screen—or create them on-the-fly when working on a section or Matrix field.
Entry types have the following settings:
- Name — Used throughout the control panel as a UI label.
- Handle — Uniquely identifies entries of this type in templates and queries.
- Icon and Color — Choose a symbol and color to subtly distinguish entries of this type throughout the control panel.
- Show the Title field — Entry titles can be set by the author or dynamically defined from other properties via an object template.
- Title Translation Method — In multi-site projects, choose how titles are localized.
- Show the Slug field — As with titles, slugs can be manually or automatically generated.
- Slug Translation Method — In multi-site projects, choose how slugs are localized.
- Show the Status field — Manually set each entry’s status, or allow it to be dictated by its usage.
- Field Layout — Add and arrange custom fields to suit your content model.
# Dynamic Entry Titles
If you want your entries’ titles to be auto-generated from a template (rather than requiring authors to enter them manually), you can uncheck the Show the Title field? checkbox. When you do, a new Title Format setting will appear.
The Title Format is an object template (just like the Entry URI Format and preview target URL Format we looked, above), and gets evaluated whenever entries with this type are saved.
# Translation Settings
Most localization behavior is determined by section and field settings, but the translation of titles and slugs is governed by entry types.
The available translation methods are covered in the custom fields documentation.
# Sections
Sections organize and expose entry types for content authors. In each section you can define the following:
- Whether entries in the section have URLs;
- What the entries’ URLs should look like;
- Which template should get loaded if an entry’s URL is requested;
- What entry types are available in the section;
- How many authors can be associated with each entry;
If your project has multiple sites, your section can define these additional settings:
- Which sites entries in the section should target;
- Which sites entries are created in, by default;
To create a new section, go to Settings → Sections and choose New Section.
# Section Types
Craft has three different types of sections:
# Singles
Singles are used for one-off pages or content objects that have unique requirements, such as…
- …a website’s homepage;
- …an About Us page;
- …a Contact Us page;
Unlike the other section types, singles only ever have one entry associated with them, meaning their URIs can be static (like contact-us
) rather than templatized (like news/{slug}
).
Singles have all the functionality of globals, and can even be pre-loaded into global Twig variables with the preloadSingles config setting. As such, singles don’t have an editable Author, Post Date, or Expiration Date.
A single’s Status controls can be hidden with the Show the Status field setting in its selected Entry Type.
# Channels
Channels are used for lists or streams of similar content, such as…
- …posts on a blog;
- …articles in a knowledge base;
- …recipes;
- …reviews;
Entries in channels are intended to be queried and displayed ordered by one or more of their attributes or custom fields. Channels are also a simple way to maintain a flat taxonomy, standing in for tags or categories.
# Structures
Structures are an extension of channels that support explicit, hierarchical organization.
Unlike other section types, structure sections expose a Structure view option on their element indexes:
Types of content that might benefit from being defined as a structure include…
- …documentation;
- …a “Services” section, where the order of services matters;
- …a company organization chart with personnel and teams;
- …editable navigation menus;
Just like channels, entries in structures can be assigned types. Structures offer great flexibility in presentation—in particular, the ability to collect nested content on a parent page, or alter the appearance of pages based on their hierarchical “depth” within a bundle of content.
Structures have the following additional settings:
- Max Levels
- Decide how many levels deep authors can organize entries.
- Default Entry Placement
- Choose where new entries are placed in the structure. This setting applies when that entry has no parent entry (before or after other “root” entries), and when a parent is selected (before or after other entries with the same parent), as well as when an entry is moved into the section. 5.3.0+
Structures can also make use of the Maintain Hierarchy setting on entries fields.
Entries belonging to a structure are discrete from nested entries in Matrix fields. Structure entries can be freely moved around in their hierarchy (receiving new “parent” elements in the process), whereas nested entries are always owned by the element they were created within.
# Custom Sources
You can supplement the automatic sources presented in the entries element index with custom sources. Each custom source lists all entries by default, but can be filtered to only those that meet the specified Entry Criteria.
# Entry URI Formats
Channel and structure sections can choose whether their entries should be assigned URLs in the system by filling in the Entry URI Format setting. Singles have a “URI” setting, but it is typically defined statically or omitted (if it doesn’t need its own URL).
The entry URI format is an object template, which gets evaluated each time an entry in the section is saved. The result is saved as the entry’s URI in the system, and is used to generate URLs (i.e. via entry.url
) and when Craft is determining how to route a request.
When Craft matches a request to an entry, its section’s designated Template is rendered. That template is automatically provided an entry
variable, set to the resolved craft\elements\Entry (opens new window) object, and ready to output any of its attributes or custom field data.
# Hierarchical URIs
Structure sections may benefit from nested paths, for child entries:
{parent.uri}/{slug}
Suppose our structure represents geographic regions on Earth. With the above Entry URI Format, a top-level “continent” entry URI might be south-america
; a nested “country” entry’s URI would then be south-america/chile
.
Structure sections might also want to include a segment before the nested path:
{parent.uri ?? 'earth'}/{slug}
The above template could also be expressed with this syntax:
{% if level == 1 %}earth{% else %}{parent.uri}{% endif %}/{slug}
With the above Entry URI Format, a top-level entry’s URI would be earth/south-america
, with a nested entry having earth/south-america/chile
.
Consider these tips for creating special URIs:
- A URI that evaluates to
__home__
(and nothing more) will be available at your site’s base path; - An empty URI means the entry does not get a route and will not have a public URL—unless you define one manually via
routes.php
; - Any Twig statement can be used to output values in a URI template—including ones that query for other elements, e.g.
{{ craft.entries().section('mySingle').one().slug }}/news
; - Aliases can be evaluated with the
alias()
function:{{ alias('@basePressUri') }}/news
,{{ alias('@mySectionUri') }}
. - The null-coalescing operator (opens new window) (
??
) can silently swallow undefined variable errors (likeparent.uri
, above);
# Nested Entry URLs
Nested entries in Matrix fields can also be configured to have URLs—but the settings are part of the field, not a section.
A single entry type may have URLs in some contexts, and not in others!
# Preview Targets Team Pro
Section can have one or more Preview Targets, or URLs where its entries are expected to be visible. This makes it possible for authors to preview entries as they are writing them in the control panel, or share a private URL with colleagues to view changes prior to publishing.
Like entry URI formats, these preview target URLs are simple Twig templates that can contain entry properties and other dynamic values.
Use single curly braces to render attributes on the entry. For example if entries in your section have their own URLs, then you can create a preview target for the entry’s primary URL using the URL template, {url}
.
Create additional preview targets for any other areas the entry might show up, such as news
, or archive/{postDate|date('Y')}
. If the entries show up on the homepage, you can create a preview target with a blank URL (unlike URI formats, a blank URL is valid, here).
Preview target URL Formats support slightly different features than for URI Formats:
- If you want to include the entry’s ID or UID in a preview target URL, use
{canonicalId}
or{canonicalUid}
rather than{id}
or{uid}
, so the source entry’s ID or UID is used rather than the draft’s; - You can use environment variables and aliases in the preview target URL. These do not get wrapped in curly braces on their own, as they are not part of the object template. Aliases may be part of a longer URI (e.g.
@headlessUrl/news/{slug}
), but environment variables can only be used on their own (e.g.$NEWS_INDEX
);
When an author is editing an entry from a section with custom preview targets, the View button will be replaced with a menu that lists the Primary entry page (if the section has an Entry URI Format), plus the names of each preview target.
If you share a link from this menu that includes a preview token, it will expire by default after one day. You can customize this with the defaultTokenDuration config setting.
The targets will also be available within Preview.
# Previewing Decoupled Front Ends
If your site’s front end lives outside of Craft (e.g. as a Vue or React app), you can still support previewing drafts and revisions with Preview or Share buttons. To do that, your front end must check for the existence of a token
query string parameter (or whatever the tokenParam setting is). If it’s in the URL, then you will need to pass that same token in the request that loads the page content. This token will cause the API request to respond with the correct content based on what the token was created to preview.
Whether you are using the Element API plugin or the built-in GraphQL API, Craft automatically injects preview elements whenever they match the query being executed.
To illustrate, suppose you were building a Nuxt (opens new window) application, and you used the file-based routing scheme (opens new window) to render blog posts: you would create pages/blog/[slug].vue
, then define a preview target in Craft with a similar path, like @nuxt/blog/{slug}
.
<script setup>
const route = useRoute();
// Construct a GraphQL fragment using the route param:
const query = `{
entry(slug: "${route.params.slug}") {
title
description
}
}`;
// Fetch the incoming token:
const token = route.query.token;
// Build the URL, with `query` and `token` params:
const { data: gql } = await useFetch('https://my-project.ddev.site/api', {
params: { query, token },
});
</script>
<template>
<article>
<h1>{{ gql.data.entry.title }}</h1>
<code>{{ gql.data.entry.uid }}</code>
</article>
</template>
This assumes you have defined a GraphQL API route of api
, and that the previewed entry will reliably have (at least) a slug set. When the token
param is omitted, Nuxt ignores it and the GraphQL API will respond as though it were any other request for an entry with the given slug.
You can pass the token via either a query string parameter named after your tokenParam config setting, or an X-Craft-Token
header.
For live preview, you should also consider enabling iFrame Resizer so that Craft can maintain the page scroll position between page loads.
# Moving Entries Between Sections 5.3.0+
Entries in channel and structure sections cane be moved to other sections that support the same entry type. Use the Move to… element action from any entry element index, then select the new section. If the action is disabled, the entry has no suitable targets—you may be able to change its entry type in-situ, reconcile any custom field changes, then move it to a compatible section.
When moving an entry, it’s important to note these behaviors:
- If the new section is a structure, the entry will be placed at the root, according to its Default Entry Placement setting.
- Drafts and revisions will be moved along with the entry and remain accessible, but only drafts that use an entry type that is allowed in the new section can be restored—same as if an entry type were removed from a section.
- If the new section has a lower Max authors setting, author data will remain intact and produce a validation error when saved.
- Authors who don’t have access to the new section will also be removed, the next time the entry is saved. Permissions are still checked based on the section, not authorship.
- Singles will never appear as targets for moving an entry.
# Nested Entries
Entries also power the Matrix and CKEditor (opens new window) fields, which means your entry types can represent entire pages, or the building blocks thereof. How you implement your content model and authoring experience is entirely up to you!
Nested entries are an implementation of nested elements, a broader category of “owned” elements that includes addresses and powers Commerce’s product and variant architecture.
# Editing Entries
If you have at least one section, there will be an Entries menu item in the primary control panel navigation. Clicking on it will take you to the entry index. From there, you can navigate to the entry you wish to edit, or create a new one.
Depending on your section’s settings, can perform some or all of the following actions from any entry’s edit screen:
- Choose the entry type (if there is more than one to choose from);
- Edit the entry’s Title, Slug, and custom field values;
- Choose the entry’s Authors Team Pro;
- Choose the entry’s Parent (if it’s within a Structure section);
- Set the entry’s Post Date (when it will be considered published);
- Set the entry’s Expiration Date (optional);
- Choose whether the entry is Enabled or not (globally, and/or per-site);
- Save changes to the entry;
- Save a new draft of the entry;
- View revisions of the entry;
- Apply changes from a derivative (draft or revision);
If you leave the Post Date blank, Craft will automatically set it the first time an entry is saved as enabled.
# Entry Creation
As soon as you click New entry, Craft creates an empty entry, and redirects you to its edit screen. This gives the system a place to auto-save your edits—effectively a new entry represented only as a draft. Internally, this is called a “fresh” entry.
Once you add some content to a fresh entry (or explicitly choose Save draft from the Create entry menu), Craft marks the draft as having been saved, and will expose it in element indexes when using the All or Draft status options.
Stray drafts (those that were created but never edited or explicitly saved) are automatically garbage-collected, respecting the purgeUnsavedDraftsDuration setting.
The entry editing lifecycle is designed to provide authors clear, actionable information about the state of their content, and to prevent unintended loss. Let’s look more closely at a few supporting features.
# Drafts
As soon as you alter a field on an entry, Craft auto-saves the changes as a provisional draft.
Subsequent edits are also saved to your provisional draft, and made available any time you view that entry in the control panel. Each user gets their own provisional draft, so your changes are private.
Pressing the Save button applies changes from a provisional draft to its canonical entry, and creates a revision (if its section supports revisions).
If you aren’t ready to publish your changes, you can instead press Create a Draft to save your work as a new draft. You may have as many regular drafts as you wish—and those drafts can have their own name and notes to help you track what you’re working on. The name of your current draft (if any) is shown at the top of the edit screen in the revision menu.
Your drafts may be visible to (and editable by) other users! While an auto-saved provisional draft is always private, the visibility of saved drafts is governed by users’ permissions for the entry’s section.
While Craft’s auto-saving behavior creates a provisional draft from the canonical entry, edits to an existing, explicitly-saved draft are saved directly to that draft—in other words, Craft doesn’t create drafts for another draft!
When your edits are ready to be published, press Apply draft to merge the changes into the canonical entry.
# Revisions
Any time you apply a draft (provisional or otherwise) to the canonical entry, Craft creates a revision. Revisions track which fields and attributes changed each time the canonical entry is updated, and provide a means to revert to previous versions of an entry. Drafts and revisions both have a creator
property that stores what user initiated the update separately from the “author.”
The revision menu only displays the ten most recent revisions. Older revisions are available via the View all revisions → link at the bottom of the menu.
Any time a revision is created, Craft pushes a job into the queue to ensure the oldest one(s) are pruned (if there are more revisions than allowed by the maxRevisions setting).
# Querying for Revisions
You can find drafts and revisions of a specific entry using the draftOf() and revisionOf() query params.
# Trash
All elements support soft-deletion. When you delete an entry, its dateDeleted
property is set to the current time, and Craft excludes it from results—unless the trashed
query param is used. Similarly, when restoring a deleted entry, its dateDeleted
is set to null
.
Entries remain in the “trashed” state until they are manually hard-deleted from the control panel or their dateDeleted
is longer ago than the softDeleteDuration setting when garbage collection runs.
The trash should not be used to temporarily remove content from your site. Restoring trashed entries is only intended as a means to recover inadvertently-deleted content—instead, use the global or site-specific Enabled settings. Entries can remain disabled indefinitely.
# Activity
Craft keeps track of user activity on entries, and will push presence pips and notifications to anyone working with drafts of the same entry.
Notifications will appear in the bottom-left corner along with other flashes, and prompt you to reload the entry if it has changed since you opened it. This can play out in a couple ways:
- If another user applied a draft to the canonical entry while you were working on a provisional draft, Craft will merge all non-conflicting edits into your provisional draft. In situations where you both made changes to a field, Craft keeps your changes.
- If only the other user made a change, the page simply refreshes to show the new canonical entry content.
Automatic merging of changes from canonical entries is nondestructive, and non-optional. Merging occurs just before an entry’s edit screen is viewed.
# Querying Entries
When Craft receives a request matching an entry’s URI, it automatically makes an entry
variable available. Everywhere else in your front-end (or PHP code), you can fetch entries using entry queries.
Once you’ve created an entry query, you can set parameters on it to narrow down the results, and then execute it by calling .one()
or .all()
to return a single Entry (opens new window) object or an array of them, respectively.
Nested entries may show up unexpectedly in some entry queries—particularly those that don’t filter by .section()
. If you want to return only entries without owners, you can use .section('*')
.
5.2.0+
# Example
We can display the 10 most recent entries in a “Blog” section by doing the following:
- Create an entry query with
craft.entries()
. - Set the section and limit parameters on it.
- Fetch the entries with
.all()
. - Loop through the entries using a for (opens new window) tag to output the blog post HTML.
{# Create an entry query with the 'section' and 'limit' parameters #}
{% set myEntryQuery = craft.entries()
.section('blog')
.limit(10) %}
{# Fetch the entries #}
{% set entries = myEntryQuery.all() %}
{# Display the entries #}
{% for entry in entries %}
<article>
<h1><a href="{{ entry.url }}">{{ entry.title }}</a></h1>
{{ entry.summary }}
<a href="{{ entry.url }}">Continue reading</a>
</article>
{% endfor %}
# Parameters
Entry queries support the following parameters:
Param | Description |
---|---|
after | Narrows the query results to only entries that were posted on or after a certain date. |
afterPopulate | Performs any post-population processing on elements. |
allowOwnerDrafts | Narrows the query results based on whether the entries’ owners are drafts. |
allowOwnerRevisions | Narrows the query results based on whether the entries’ owners are revisions. |
ancestorDist | Narrows the query results to only entries that are up to a certain distance away from the entry specified by ancestorOf. |
ancestorOf | Narrows the query results to only entries that are ancestors of another entry in its structure. |
andNotRelatedTo | Narrows the query results to only entries that are not related to certain other elements. |
andRelatedTo | Narrows the query results to only entries that are related to certain other elements. |
asArray | Causes the query to return matching entries as arrays of data, rather than Entry (opens new window) objects. |
authorGroup | Narrows the query results based on the user group the entries’ authors belong to. |
authorGroupId | Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs. |
authorId | Narrows the query results based on the entries’ author ID(s). |
before | Narrows the query results to only entries that were posted before a certain date. |
cache | Enables query cache for this Query. |
clearCachedResult | Clears the cached result (opens new window). |
dateCreated | Narrows the query results based on the entries’ creation dates. |
dateUpdated | Narrows the query results based on the entries’ last-updated dates. |
descendantDist | Narrows the query results to only entries that are up to a certain distance away from the entry specified by descendantOf. |
descendantOf | Narrows the query results to only entries that are descendants of another entry in its structure. |
draftCreator | Narrows the query results to only drafts created by a given user. |
draftId | Narrows the query results based on the entries’ draft’s ID (from the drafts table). |
draftOf | Narrows the query results to only drafts of a given entry. |
drafts | Narrows the query results to only drafts entries. |
eagerly | Causes the query to be used to eager-load results for the query’s source element and any other elements in its collection. |
expiryDate | Narrows the query results based on the entries’ expiry dates. |
field | Narrows the query results based on the field the entries are contained by. |
fieldId | Narrows the query results based on the field the entries are contained by, per the fields’ IDs. |
fixedOrder | Causes the query results to be returned in the order specified by id. |
hasDescendants | Narrows the query results based on whether the entries have any descendants in their structure. |
id | Narrows the query results based on the entries’ IDs. |
ignorePlaceholders | Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by craft\services\Elements::setPlaceholderElement() (opens new window). |
inBulkOp | Narrows the query results to only entries 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 entries should be queried in, based on their language. |
leaves | Narrows the query results based on whether the entries are “leaves” (entries with no descendants). |
level | Narrows the query results based on the entries’ level within the structure. |
limit | Determines the number of entries that should be returned. |
nextSiblingOf | Narrows the query results to only the entry that comes immediately after another entry in its structure. |
notRelatedTo | Narrows the query results to only entries that are not related to certain other elements. |
offset | Determines how many entries should be skipped in the results. |
orderBy | Determines the order that the entries should be returned in. (If empty, defaults to postDate DESC, elements.id , or the order defined by the section if the section or sectionId params are set to a single Structure section.) |
owner | Sets the ownerId and siteId parameters based on a given element. |
ownerId | Narrows the query results based on the owner element of the entries, per the owners’ IDs. |
positionedAfter | Narrows the query results to only entries that are positioned after another entry in its structure. |
positionedBefore | Narrows the query results to only entries that are positioned before another entry in its structure. |
postDate | Narrows the query results based on the entries’ post dates. |
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). |
prevSiblingOf | Narrows the query results to only the entry that comes immediately before another entry in its structure. |
primaryOwner | Sets the primaryOwnerId and siteId parameters based on a given element. |
primaryOwnerId | Narrows the query results based on the primary owner element of the entries, per the owners’ IDs. |
provisionalDrafts | Narrows the query results to only provisional drafts. |
relatedTo | Narrows the query results to only entries that are related to certain other elements. |
render | Executes the query and renders the resulting elements using their partial templates. |
revisionCreator | Narrows the query results to only revisions created by a given user. |
revisionId | Narrows the query results based on the entries’ revision’s ID (from the revisions table). |
revisionOf | Narrows the query results to only revisions of a given entry. |
revisions | Narrows the query results to only revision entries. |
savable | Sets the savable (opens new window) property. |
savedDraftsOnly | Narrows the query results to only unpublished drafts which have been saved after initial creation. |
search | Narrows the query results to only entries that match a search query. |
section | Narrows the query results based on the sections the entries belong to. |
sectionId | Narrows the query results based on the sections the entries belong to, per the sections’ IDs. |
siblingOf | Narrows the query results to only entries that are siblings of another entry in its structure. |
site | Determines which site(s) the entries should be queried in. |
siteId | Determines which site(s) the entries should be queried in, per the site’s ID. |
siteSettingsId | Narrows the query results based on the entries’ IDs in the elements_sites table. |
slug | Narrows the query results based on the entries’ slugs. |
status | Narrows the query results based on the entries’ statuses. |
title | Narrows the query results based on the entries’ titles. |
trashed | Narrows the query results to only entries that have been soft-deleted. |
type | Narrows the query results based on the entries’ entry types. |
typeId | Narrows the query results based on the entries’ entry types, per the types’ IDs. |
uid | Narrows the query results based on the entries’ UIDs. |
unique | Determines whether only elements with unique IDs should be returned by the query. |
uri | Narrows the query results based on the entries’ 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 entries eager-loaded with related elements. |
withCustomFields | Sets whether custom fields should be factored into the query. |
# after
Narrows the query results to only entries that were posted on or after a certain date.
Possible values include:
Value | Fetches entries… |
---|---|
'2018-04-01' | that were posted on or after 2018-04-01. |
a DateTime (opens new window) object | that were posted on or after the date represented by the object. |
now /today /tomorrow /yesterday | that were posted on or after midnight of the specified relative date. |
{# Fetch entries posted this month #}
{% set firstDayOfMonth = date('first day of this month') %}
{% set entries = craft.entries()
.after(firstDayOfMonth)
.all() %}
# afterPopulate
Performs any post-population processing on elements.
# allowOwnerDrafts
Narrows the query results based on whether the entries’ owners are drafts.
Possible values include:
Value | Fetches entries… |
---|---|
true | which can belong to a draft. |
false | which cannot belong to a draft. |
# allowOwnerRevisions
Narrows the query results based on whether the entries’ owners are revisions.
Possible values include:
Value | Fetches entries… |
---|---|
true | which can belong to a revision. |
false | which cannot belong to a revision. |
# ancestorDist
Narrows the query results to only entries that are up to a certain distance away from the entry specified by ancestorOf.
{# Fetch entries above this one #}
{% set entries = craft.entries()
.ancestorOf(myEntry)
.ancestorDist(3)
.all() %}
# ancestorOf
Narrows the query results to only entries that are ancestors of another entry in its structure.
Possible values include:
Value | Fetches entries… |
---|---|
1 | above the entry with an ID of 1. |
a Entry (opens new window) object | above the entry represented by the object. |
{# Fetch entries above this one #}
{% set entries = craft.entries()
.ancestorOf(myEntry)
.all() %}
This can be combined with ancestorDist if you want to limit how far away the ancestor entries can be.
# andNotRelatedTo
Narrows the query results to only entries that are not related to certain other elements.
See Relations (opens new window) for a full explanation of how to work with this parameter.
{# Fetch all entries that are related to myCategoryA and not myCategoryB #}
{% set entries = craft.entries()
.relatedTo(myCategoryA)
.andNotRelatedTo(myCategoryB)
.all() %}
# andRelatedTo
Narrows the query results to only entries that are related to certain other elements.
See Relations (opens new window) for a full explanation of how to work with this parameter.
{# Fetch all entries that are related to myCategoryA and myCategoryB #}
{% set entries = craft.entries()
.relatedTo(myCategoryA)
.andRelatedTo(myCategoryB)
.all() %}
# asArray
Causes the query to return matching entries as arrays of data, rather than Entry (opens new window) objects.
# authorGroup
Narrows the query results based on the user group the entries’ authors belong to.
Possible values include:
Value | Fetches entries… |
---|---|
'foo' | with an author in a group with a handle of foo . |
'not foo' | not with an author in a group with a handle of foo . |
['foo', 'bar'] | with an author in a group with a handle of foo or bar . |
['not', 'foo', 'bar'] | not with an author in a group with a handle of foo or bar . |
a UserGroup (opens new window) object | with an author in a group represented by the object. |
an array of UserGroup (opens new window) objects | with an author in a group represented by the objects. |
{# Fetch entries with an author in the Foo user group #}
{% set entries = craft.entries()
.authorGroup('foo')
.all() %}
# authorGroupId
Narrows the query results based on the user group the entries’ authors belong to, per the groups’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
1 | with an author in a group with an ID of 1. |
'not 1' | not with an author in a group with an ID of 1. |
[1, 2] | with an author in a group with an ID of 1 or 2. |
['not', 1, 2] | not with an author in a group with an ID of 1 or 2. |
{# Fetch entries with an author in a group with an ID of 1 #}
{% set entries = craft.entries()
.authorGroupId(1)
.all() %}
# authorId
Narrows the query results based on the entries’ author ID(s).
Possible values include:
Value | Fetches entries… |
---|---|
1 | with an author with an ID of 1. |
'not 1' | not with an author with an ID of 1. |
[1, 2] | with an author with an ID of 1 or 2. |
['and', 1, 2] | with authors with IDs of 1 and 2. |
['not', 1, 2] | not with an author with an ID of 1 or 2. |
{# Fetch entries with an author with an ID of 1 #}
{% set entries = craft.entries()
.authorId(1)
.all() %}
# before
Narrows the query results to only entries that were posted before a certain date.
Possible values include:
Value | Fetches entries… |
---|---|
'2018-04-01' | that were posted before 2018-04-01. |
a DateTime (opens new window) object | that were posted before the date represented by the object. |
now /today /tomorrow /yesterday | that were posted before midnight of specified relative date. |
{# Fetch entries posted before this month #}
{% set firstDayOfMonth = date('first day of this month') %}
{% set entries = craft.entries()
.before(firstDayOfMonth)
.all() %}
# cache
Enables query cache for this Query.
# clearCachedResult
Clears the cached result (opens new window).
# dateCreated
Narrows the query results based on the entries’ creation dates.
Possible values include:
Value | Fetches entries… |
---|---|
'>= 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. |
{# Fetch entries created last month #}
{% set start = date('first day of last month')|atom %}
{% set end = date('first day of this month')|atom %}
{% set entries = craft.entries()
.dateCreated(['and', ">= #{start}", "< #{end}"])
.all() %}
# dateUpdated
Narrows the query results based on the entries’ last-updated dates.
Possible values include:
Value | Fetches entries… |
---|---|
'>= 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. |
{# Fetch entries updated in the last week #}
{% set lastWeek = date('1 week ago')|atom %}
{% set entries = craft.entries()
.dateUpdated(">= #{lastWeek}")
.all() %}
# descendantDist
Narrows the query results to only entries that are up to a certain distance away from the entry specified by descendantOf.
{# Fetch entries below this one #}
{% set entries = craft.entries()
.descendantOf(myEntry)
.descendantDist(3)
.all() %}
# descendantOf
Narrows the query results to only entries that are descendants of another entry in its structure.
Possible values include:
Value | Fetches entries… |
---|---|
1 | below the entry with an ID of 1. |
a Entry (opens new window) object | below the entry represented by the object. |
{# Fetch entries below this one #}
{% set entries = craft.entries()
.descendantOf(myEntry)
.all() %}
This can be combined with descendantDist if you want to limit how far away the descendant entries can be.
# draftCreator
Narrows the query results to only drafts created by a given user.
Possible values include:
Value | Fetches drafts… |
---|---|
1 | created by the user with an ID of 1. |
a craft\elements\User (opens new window) object | created by the user represented by the object. |
{# Fetch drafts by the current user #}
{% set entries = craft.entries()
.draftCreator(currentUser)
.all() %}
# draftId
Narrows the query results based on the entries’ draft’s ID (from the drafts
table).
Possible values include:
Value | Fetches drafts… |
---|---|
1 | for the draft with an ID of 1. |
# draftOf
Narrows the query results to only drafts of a given entry.
Possible values include:
Value | Fetches drafts… |
---|---|
1 | for the entry with an ID of 1. |
[1, 2] | for the entries with an ID of 1 or 2. |
a Entry (opens new window) object | for the entry represented by the object. |
an array of Entry (opens new window) objects | for the entries represented by the objects. |
'*' | for any entry |
false | that aren’t associated with a published entry |
{# Fetch drafts of the entry #}
{% set entries = craft.entries()
.draftOf(myEntry)
.all() %}
# drafts
Narrows the query results to only drafts entries.
# eagerly
Causes the query to be used to eager-load results for the query’s source element and any other elements in its collection.
# expiryDate
Narrows the query results based on the entries’ expiry dates.
Possible values include:
Value | Fetches entries… |
---|---|
':empty:' | that don’t have an expiry date. |
':notempty:' | that have an expiry date. |
'>= 2020-04-01' | that will expire on or after 2020-04-01. |
'< 2020-05-01' | that will expire before 2020-05-01 |
['and', '>= 2020-04-04', '< 2020-05-01'] | that will expire between 2020-04-01 and 2020-05-01. |
now /today /tomorrow /yesterday | that expire at midnight of the specified relative date. |
{# Fetch entries expiring this month #}
{% set nextMonth = date('first day of next month')|atom %}
{% set entries = craft.entries()
.expiryDate("< #{nextMonth}")
.all() %}
# field
Narrows the query results based on the field the entries are contained by.
Possible values include:
Value | Fetches entries… |
---|---|
'foo' | in a field with a handle of foo . |
['foo', 'bar'] | in a field with a handle of foo or bar . |
a \craft\elements\db\craft\fields\Matrix object | in a field represented by the object. |
{# Fetch entries in the Foo field #}
{% set entries = craft.entries()
.field('foo')
.all() %}
# fieldId
Narrows the query results based on the field the entries are contained by, per the fields’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
1 | in a field with an ID of 1. |
'not 1' | not in a field with an ID of 1. |
[1, 2] | in a field with an ID of 1 or 2. |
['not', 1, 2] | not in a field with an ID of 1 or 2. |
{# Fetch entries in the field with an ID of 1 #}
{% set entries = craft.entries()
.fieldId(1)
.all() %}
# fixedOrder
Causes the query results to be returned in the order specified by id.
If no IDs were passed to id, setting this to true
will result in an empty result set.
{# Fetch entries in a specific order #}
{% set entries = craft.entries()
.id([1, 2, 3, 4, 5])
.fixedOrder()
.all() %}
# hasDescendants
Narrows the query results based on whether the entries have any descendants in their structure.
(This has the opposite effect of calling leaves.)
{# Fetch entries that have descendants #}
{% set entries = craft.entries()
.hasDescendants()
.all() %}
# id
Narrows the query results based on the entries’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
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. |
This can be combined with fixedOrder if you want the results to be returned in a specific order.
# ignorePlaceholders
Causes the query to return matching entries as they are stored in the database, ignoring matching placeholder elements that were set by craft\services\Elements::setPlaceholderElement() (opens new window).
# inBulkOp
Narrows the query results to only entries 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 entries should be queried in, based on their language.
Possible values include:
Value | Fetches entries… |
---|---|
'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 . |
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.
{# Fetch entries from English sites #}
{% set entries = craft.entries()
.language('en')
.all() %}
# leaves
Narrows the query results based on whether the entries are “leaves” (entries with no descendants).
(This has the opposite effect of calling hasDescendants.)
{# Fetch entries that have no descendants #}
{% set entries = craft.entries()
.leaves()
.all() %}
# level
Narrows the query results based on the entries’ level within the structure.
Possible values include:
Value | Fetches entries… |
---|---|
1 | with a level of 1. |
'not 1' | not with a level of 1. |
'>= 3' | with a level greater than or equal to 3. |
[1, 2] | with a level of 1 or 2. |
[null, 1] | without a level, or a level of 1. |
['not', 1, 2] | not with level of 1 or 2. |
{# Fetch entries positioned at level 3 or above #}
{% set entries = craft.entries()
.level('>= 3')
.all() %}
# limit
Determines the number of entries that should be returned.
# nextSiblingOf
Narrows the query results to only the entry that comes immediately after another entry in its structure.
Possible values include:
Value | Fetches the entry… |
---|---|
1 | after the entry with an ID of 1. |
a Entry (opens new window) object | after the entry represented by the object. |
# notRelatedTo
Narrows the query results to only entries that are not related to certain other elements.
See Relations (opens new window) for a full explanation of how to work with this parameter.
{# Fetch all entries that are related to myEntry #}
{% set entries = craft.entries()
.notRelatedTo(myEntry)
.all() %}
# offset
Determines how many entries should be skipped in the results.
{# Fetch all entries except for the first 3 #}
{% set entries = craft.entries()
.offset(3)
.all() %}
# orderBy
Determines the order that the entries should be returned in. (If empty, defaults to postDate DESC, elements.id
, or the order defined by the section if the section or sectionId params are set to a single Structure section.)
{# Fetch all entries in order of date created #}
{% set entries = craft.entries()
.orderBy('dateCreated ASC')
.all() %}
# owner
Sets the ownerId and siteId parameters based on a given element.
{# Fetch entries created for this entry #}
{% set entries = craft.entries()
.owner(myEntry)
.all() %}
# ownerId
Narrows the query results based on the owner element of the entries, per the owners’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
1 | created for an element with an ID of 1. |
[1, 2] | created for an element with an ID of 1 or 2. |
{# Fetch entries created for an element with an ID of 1 #}
{% set entries = craft.entries()
.ownerId(1)
.all() %}
# positionedAfter
Narrows the query results to only entries that are positioned after another entry in its structure.
Possible values include:
Value | Fetches entries… |
---|---|
1 | after the entry with an ID of 1. |
a Entry (opens new window) object | after the entry represented by the object. |
{# Fetch entries after this one #}
{% set entries = craft.entries()
.positionedAfter(myEntry)
.all() %}
# positionedBefore
Narrows the query results to only entries that are positioned before another entry in its structure.
Possible values include:
Value | Fetches entries… |
---|---|
1 | before the entry with an ID of 1. |
a Entry (opens new window) object | before the entry represented by the object. |
{# Fetch entries before this one #}
{% set entries = craft.entries()
.positionedBefore(myEntry)
.all() %}
# postDate
Narrows the query results based on the entries’ post dates.
Possible values include:
Value | Fetches entries… |
---|---|
'>= 2018-04-01' | that were posted on or after 2018-04-01. |
'< 2018-05-01' | that were posted before 2018-05-01. |
['and', '>= 2018-04-04', '< 2018-05-01'] | that were posted between 2018-04-01 and 2018-05-01. |
now /today /tomorrow /yesterday | that were posted at midnight of the specified relative date. |
{# Fetch entries posted last month #}
{% set start = date('first day of last month')|atom %}
{% set end = date('first day of this month')|atom %}
{% set entries = craft.entries()
.postDate(['and', ">= #{start}", "< #{end}"])
.all() %}
# preferSites
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.
{# Fetch unique entries from Site A, or Site B if they don’t exist in Site A #}
{% set entries = craft.entries()
.site('*')
.unique()
.preferSites(['a', 'b'])
.all() %}
# prepForEagerLoading
Prepares the query for lazy eager loading.
# prepareSubquery
Prepares the element query and returns its subquery (which determines what elements will be returned).
# prevSiblingOf
Narrows the query results to only the entry that comes immediately before another entry in its structure.
Possible values include:
Value | Fetches the entry… |
---|---|
1 | before the entry with an ID of 1. |
a Entry (opens new window) object | before the entry represented by the object. |
{# Fetch the previous entry #}
{% set entry = craft.entries()
.prevSiblingOf(myEntry)
.one() %}
# primaryOwner
Sets the primaryOwnerId and siteId parameters based on a given element.
{# Fetch entries created for this entry #}
{% set entries = craft.entries()
.primaryOwner(myEntry)
.all() %}
# primaryOwnerId
Narrows the query results based on the primary owner element of the entries, per the owners’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
1 | created for an element with an ID of 1. |
[1, 2] | created for an element with an ID of 1 or 2. |
{# Fetch entries created for an element with an ID of 1 #}
{% set entries = craft.entries()
.primaryOwnerId(1)
.all() %}
# provisionalDrafts
Narrows the query results to only provisional drafts.
{# Fetch provisional drafts created by the current user #}
{% set entries = craft.entries()
.provisionalDrafts()
.draftCreator(currentUser)
.all() %}
# relatedTo
Narrows the query results to only entries that are related to certain other elements.
See Relations (opens new window) for a full explanation of how to work with this parameter.
{# Fetch all entries that are related to myCategory #}
{% set entries = craft.entries()
.relatedTo(myCategory)
.all() %}
# render
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.
# revisionCreator
Narrows the query results to only revisions created by a given user.
Possible values include:
Value | Fetches revisions… |
---|---|
1 | created by the user with an ID of 1. |
a craft\elements\User (opens new window) object | created by the user represented by the object. |
{# Fetch revisions by the current user #}
{% set entries = craft.entries()
.revisionCreator(currentUser)
.all() %}
# revisionId
Narrows the query results based on the entries’ revision’s ID (from the revisions
table).
Possible values include:
Value | Fetches revisions… |
---|---|
1 | for the revision with an ID of 1. |
# revisionOf
Narrows the query results to only revisions of a given entry.
Possible values include:
Value | Fetches revisions… |
---|---|
1 | for the entry with an ID of 1. |
a Entry (opens new window) object | for the entry represented by the object. |
{# Fetch revisions of the entry #}
{% set entries = craft.entries()
.revisionOf(myEntry)
.all() %}
# revisions
Narrows the query results to only revision entries.
{# Fetch a revision entry #}
{% set entries = craft.entries()
.revisions()
.id(123)
.one() %}
# savable
Sets the savable (opens new window) property.
# savedDraftsOnly
Narrows the query results to only unpublished drafts which have been saved after initial creation.
{# Fetch saved, unpublished draft entries #}
{% set entries = craft.entries()
.draftOf(false)
.savedDraftsOnly()
.all() %}
# search
Narrows the query results to only entries that match a search query.
See Searching (opens new window) for a full explanation of how to work with this parameter.
{# Get the search query from the 'q' query string param #}
{% set searchQuery = craft.app.request.getQueryParam('q') %}
{# Fetch all entries that match the search query #}
{% set entries = craft.entries()
.search(searchQuery)
.all() %}
# section
Narrows the query results based on the sections the entries belong to.
Possible values include:
Value | Fetches entries… |
---|---|
'foo' | in a section with a handle of foo . |
'not foo' | not in a section with a handle of foo . |
['foo', 'bar'] | in a section with a handle of foo or bar . |
['not', 'foo', 'bar'] | not in a section with a handle of foo or bar . |
a Section (opens new window) object | in a section represented by the object. |
'*' | in any section. |
{# Fetch entries in the Foo section #}
{% set entries = craft.entries()
.section('foo')
.all() %}
# sectionId
Narrows the query results based on the sections the entries belong to, per the sections’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
1 | in a section with an ID of 1. |
'not 1' | not in a section with an ID of 1. |
[1, 2] | in a section with an ID of 1 or 2. |
['not', 1, 2] | not in a section with an ID of 1 or 2. |
{# Fetch entries in the section with an ID of 1 #}
{% set entries = craft.entries()
.sectionId(1)
.all() %}
# siblingOf
Narrows the query results to only entries that are siblings of another entry in its structure.
Possible values include:
Value | Fetches entries… |
---|---|
1 | beside the entry with an ID of 1. |
a Entry (opens new window) object | beside the entry represented by the object. |
{# Fetch entries beside this one #}
{% set entries = craft.entries()
.siblingOf(myEntry)
.all() %}
# site
Determines which site(s) the entries should be queried in.
The current site will be used by default.
Possible values include:
Value | Fetches entries… |
---|---|
'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 (opens new window) object | from the site represented by the object. |
'*' | from any site. |
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.
{# Fetch entries from the Foo site #}
{% set entries = craft.entries()
.site('foo')
.all() %}
# siteId
Determines which site(s) the entries should be queried in, per the site’s ID.
The current site will be used by default.
Possible values include:
Value | Fetches entries… |
---|---|
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. |
{# Fetch entries from the site with an ID of 1 #}
{% set entries = craft.entries()
.siteId(1)
.all() %}
# siteSettingsId
Narrows the query results based on the entries’ IDs in the elements_sites
table.
Possible values include:
Value | Fetches entries… |
---|---|
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. |
{# Fetch the entry by its ID in the elements_sites table #}
{% set entry = craft.entries()
.siteSettingsId(1)
.one() %}
# slug
Narrows the query results based on the entries’ slugs.
Possible values include:
Value | Fetches entries… |
---|---|
'foo' | with a slug of foo . |
'foo*' | with a slug that begins with foo . |
'*foo' | with a slug that ends with foo . |
'*foo*' | with a slug that contains foo . |
'not *foo*' | with a slug that doesn’t contain foo . |
['*foo*', '*bar*'] | with a slug that contains foo or bar . |
['not', '*foo*', '*bar*'] | with a slug that doesn’t contain foo or bar . |
{# Get the requested entry slug from the URL #}
{% set requestedSlug = craft.app.request.getSegment(3) %}
{# Fetch the entry with that slug #}
{% set entry = craft.entries()
.slug(requestedSlug|literal)
.one() %}
# status
Narrows the query results based on the entries’ statuses.
Possible values include:
Value | Fetches entries… |
---|---|
'live' (default) | that are live. |
'pending' | that are pending (enabled with a Post Date in the future). |
'expired' | that are expired (enabled with an Expiry Date in the past). |
'disabled' | that are disabled. |
['live', 'pending'] | that are live or pending. |
['not', 'live', 'pending'] | that are not live or pending. |
# title
Narrows the query results based on the entries’ titles.
Possible values include:
Value | Fetches entries… |
---|---|
'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 . |
{# Fetch entries with a title that contains "Foo" #}
{% set entries = craft.entries()
.title('*Foo*')
.all() %}
# trashed
Narrows the query results to only entries that have been soft-deleted.
# type
Narrows the query results based on the entries’ entry types.
Possible values include:
Value | Fetches entries… |
---|---|
'foo' | of a type with a handle of foo . |
'not foo' | not of a type with a handle of foo . |
['foo', 'bar'] | of a type with a handle of foo or bar . |
['not', 'foo', 'bar'] | not of a type with a handle of foo or bar . |
an EntryType (opens new window) object | of a type represented by the object. |
{# Fetch entries in the Foo section with a Bar entry type #}
{% set entries = craft.entries()
.section('foo')
.type('bar')
.all() %}
# typeId
Narrows the query results based on the entries’ entry types, per the types’ IDs.
Possible values include:
Value | Fetches entries… |
---|---|
1 | of a type with an ID of 1. |
'not 1' | not of a type with an ID of 1. |
[1, 2] | of a type with an ID of 1 or 2. |
['not', 1, 2] | not of a type with an ID of 1 or 2. |
{# Fetch entries of the entry type with an ID of 1 #}
{% set entries = craft.entries()
.typeId(1)
.all() %}
# uid
Narrows the query results based on the entries’ UIDs.
{# Fetch the entry by its UID #}
{% set entry = craft.entries()
.uid('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
.one() %}
# unique
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.
{# Fetch unique entries across all sites #}
{% set entries = craft.entries()
.site('*')
.unique()
.all() %}
# uri
Narrows the query results based on the entries’ URIs.
Possible values include:
Value | Fetches entries… |
---|---|
'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 . |
{# Get the requested URI #}
{% set requestedUri = craft.app.request.getPathInfo() %}
{# Fetch the entry with that URI #}
{% set entry = craft.entries()
.uri(requestedUri|literal)
.one() %}
# 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 entries eager-loaded with related elements.
See Eager-Loading Elements (opens new window) for a full explanation of how to work with this parameter.
{# Fetch entries eager-loaded with the "Related" field’s relations #}
{% set entries = craft.entries()
.with(['related'])
.all() %}
# withCustomFields
Sets whether custom fields should be factored into the query.