TransWikia.com

How to return a specific entry?

Craft CMS Asked by pumkincreative on September 4, 2021

Hopefully this is a simple question but I couldn’t find a clear answer anywhere – I just want to be able to pull in data from a specific entry, where I know the identifier.

In this particular case, the entry is a single. Currently I’m doing this:

{% set entry = craft.entries.section('myChosenSection').first() %}

Is this correct, or is there a more concise way?

3 Answers

This is the correct way.

Examples:

Singles:

{% set entry = craft.entries.section('section_handle').one() %}

Channels / Structures:

{% set entry = craft.entries.section('section_handle').slug('my_slug').one() %}

General:

{% set entry = craft.entries.id(5).one() %}

See craft.entries for a list of all properties.

Correct answer by Victor In on September 4, 2021

An alternate way would be to use Twig's |filter() to do the filtering rather than Craft itself.

I can't say how much of a performance difference it makes, but I know that if you're doing very large queries many times, without adequate caching, it could slow your site down if you're constantly making multiple entry queries.

It also allows a bit more flexibility if you're trying to do something non-standard or need a function callback. For example, I wanted to create an array of IDs in Twig and then choose the first entry that matched it, and |filter() worked well in that situation.

{% set featured = [18, 56, 105] %}
{% set entries = craft.entries.section('myChosenSection').all() %}
{% set chosenEntry = entries|filter((entry) => entry.id in featured)|first %}

Answered by Matt Fletcher on September 4, 2021

I realize this question was geared towards getting the entry via twig. Here is how you could accomplish the same from a plugin. In my case, I wanted to find an entry via slug.

MyPluginController.php

public function actionMyAction() {
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'mySectionHandle';
    $criteria->slug = $this->_getLastSegment(craft()->request->getUrlReferrer());
    ...

    $entries = $criteria->find();

    if ($entries) {
        foreach ($criteria as $entry) {
            error_log($entry->title);
        }
    } else {
        // No entry found that matches criteria.
    }
}

private function _getLastSegment($url)
{
    $path = parse_url($url, PHP_URL_PATH);
    $trimmed = trim($path, '/');
    $tokens = explode('/', $trimmed);

    return end($tokens);
}

Answered by Damon on September 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP