1

I build a search component, and it works fine. Now I would like to show all the uploaded assets from a specific page ("Downloads") in the search results that include the search key.

How can I do that with Craft?

2

You can use craft.assets() to search for assets, the same way you can use craft.entries() to find entries. See Querying Assets for details. Asset queries allow you to use mostly the same methods that entry queries do. For example, you can also use the .search method to search for keywords in the asset's title and searchable fields.

{% set searchQuery = craft.app.request.getQueryParam('q') %}

{% set foundAssets = craft.assets()
    .search(searchQuery)
    .all()
%}

Limiting the search to assets that are selected on a specific entry can be done using the relatedTo method:

{% set downloadsPage = craft.entries().section('downloads').one() %}
{% set foundAssets = craft.assets()
    .search(searchQuery)
    .relatedTo(downloadsPage)
    .all()
%}

See the documentation linked above for more information (for example, how to limit the relation to a specific field and direction).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.