2

I am trying to get a query to work using the id() param on a craft.entries.find() call and am stuck getting nothing back from Craft.

We are getting an array of entry IDs from a CRM to personalize the content on the page which we then are fetching from Craft. At the same time we want to also omit certain IDs so we do not have duplicate entries on the same page.

{% set entryQuery = 'and, ' ~ topViewedArticlesIds|join(',') ~ ',' ~ presentArticles|join(',not ') %}

{% set topViewed = craft.entries.find({
       section: 'articles',
       id: entryQuery
}) %}

I have used the id field before to omit certain entries but I have not combined them before so this may not even be possible in this via the id field.

Any help would be greatly appreciated!

2

When you use the id parameter (without the not directive), Craft will actually only return entries matching the IDs you pass in and nothing else, which means that both including and excluding a list of IDs in the same query is redundant.

Since you already have an array of IDs you want (topViewedArticlesIds) and an array of IDs you don't want (presentArticles), it's simply a matter of creating a third array of entry IDs that includes all the IDs in the former, without any of the IDs in the latter, and pass that in to craft.entries.

Fortunately, the without filter makes this super-easy:

{% set entryIds = topViewedArticlesIds|without(presentArticles) %}

{% set entries = craft.entries({
    section: 'articles',
    id: entryIds
}) %}

Note: If you want to make sure that the order of the returned entries is in the same order as the IDs in the topViewedArticlesIds array, you can pass in the fixedOrder parameter:

{% set entries = craft.entries({
    section: 'articles',
    id: entryIds,
    fixedOrder: true
}) %}
  • Wow awesome! Will give this a try! – mcclaskiem Apr 27 '17 at 12:42
  • 1
    UPDATE: this works perfectly! Thank you! – mcclaskiem Apr 27 '17 at 13:00

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.