This article explains how to utilize the search function in the CMS Statamic using PHP code. Let's take a look at the following code example:
use Statamic\Facades\Search;
$builder = Search::index('default')
->ensureExists()
->search('This is my search query')
->where('status', 'published');
$results = $builder->limit(5)->get();
foreach ($results as $result) {
echo $result->getCpTitle().PHP_EOL;
}
First, we initialize the search, set the search index to default
, and ensure it exists. Next, we set "This is my search query" as our search query. Additionally, we define that only content with the published
status should be sought.
In the following step, we set a limit of 5
, to return a maximum of five results. Then, we iterate through the results and output the title of each result. Please note that due to the previously established limit, no more than five titles will be output.