Craft CMS Asked by nfq on September 4, 2021
I need to get the currentSite in Element API. How can this be achieved? Is it as a slug in the endpoint URL? or as a Query param? Here is the current code:
<?php
use craftelementsEntry;
use crafthelpersUrlHelper;
use craftservicesSites;
return [
'defaults' => [
'resourceKey' => 'suggestions',
'cache' => false,
'paginate' => false,
'pretty' => true,
],
'endpoints' => [
'api/search.json' => function() {
$searchQuery = Craft::$app->request->getQueryParam('query');
$site = Craft::$app->request->getQueryParam('site');
$sectionHandles = [
'pages',
'news',
];
// Search criterias
$criteria = [
'section' => $sectionHandles,
'search' => $searchQuery,
'site' => $site,
'orderBy' => 'score',
'limit' => 10,
];
return [
'elementType' => Entry::class,
'criteria' => $criteria,
'paginate' => false,
'transformer' => function(craftelementsEntry $entry) {
return [
'title' => $entry->title,
'url' => $entry->url,
];
},
];
},
]
];
The currentSite
property from the Sites service is what you're looking for. Here's how you would use it:
'api/search.json' => function() {
$siteHandle = Craft::$app->getSites()->currentSite->handle;
...
$criteria = [
'site' => $siteHandle,
...
];
return [
...
];
},
Correct answer by Jalen Davenport on September 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP