craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 56 forks source link

Example for pulling entries based on a tag or tags #85

Closed arifje closed 4 years ago

arifje commented 5 years ago

I am looking for a way to pull entries with a specific tag. Is this possible and if so, how?

EDIT: and also based on a search keyword in the title and/or description. I tried to change the criteria, but no luck:

'criteria' => ['like', 'title', 'keyword' ],

Thanks in advance!

brandonkelly commented 4 years ago

If you want to only get entries that have a specific tag selected, based on the tag’s slug, you could do this:

use craft\elements\Entry;
use craft\elements\Tag;
use craft\helpers\Db;
use yii\web\NotFoundHttpException;

'your/endpoint/pattern/<tagSlug:\w+>' => function(string $tagSlug) {
    // Get the tag
    $tag = Tag::find()
        ->group('tagGroupHandle')
        ->slug(Db::escapeParam($tagSlug))
        ->one();

    // If the tag doesn't exist, return a 404 error
    if (!$tag) {
        throw new NotFoundHttpException('Tag not found: ' . $tagSlug);
    }

    return [
        'elementType' => Entry::class,
        'criteria' => [
            'relatedTo' => ['targetElement' => $tag],
            // ...
        ],
        // ...
    ];
},

EDIT: and also based on a search keyword in the title and/or description. I tried to change the criteria, but no luck:

If you just want to find entries that match a generic search keyword, and search across the Tags field, the titles, and other custom fields, just use the search param. At this point I’m guessing you’d also want the keyword to be a query string param (such as q) rather than part of the actual endpoint URI, so we’ll leave it out of the endpoint URI pattern.

use craft\elements\Entry;

'your/endpoint/patter' => function() {
    return [
        'elementType' => Entry::class,
        'criteria' => [
            'search' => Craft::$app->request->getQueryParam('q'),
            // ...
        ],
        // ...
    ];
},