7

I want to display the current entry's index - like in this post Get entry index.

However my entries are in a structure section type not a channel, so they are not ordered by date.

Is is possible to edit the solution (below) from the above post so that it is not sorting the entries by date but rather retaining the custom order of the structure?

{# Get this entry + all entries posted before it #}
{% set postDateParam = '<= ' ~ entry.postDate|date('c') %}
{% set entryIds = craft.entries.section('news')
  .order('postDate asc').postDate(postDateParam).ids() %}

{# Count them #}
{% set position = entryIds|length %}

{{ position }}
10

I found the clue for how to do this in the getPrevSibling documentation:

getPrevSibling() will return the previous sibling whether or not it’s enabled. If you want to get the closest enabled sibling, you can do this instead:

{% set prevSibling = craft.entries.positionedBefore(entry).order('lft desc').first() %}

So this query will get the number of enabled previous siblings:

{% set prevSibsCount = craft.entries.positionedBefore(entry).total() %}

And then your position will be that + 1:

{% set position = prevSibsCount + 1 %}
{{ position }}
  • I didn't know how to do it either until you asked. – Marion Newlevant Jul 13 '15 at 2:35
  • Wow. Good job in finding the best hidden craft.entries param, @Marion! – carlcs Jul 13 '15 at 20:09
1

The accepted answer only works for single-level structures, since positionedBefore() doesn't include its parent entry. I don't know why this is, maybe it's a bug? Anyways, the result is that first child entry will get the same "index" as their parent.

e.g.

  • Home (1)
  • About (2)
    • Company (2)
    • Contact (3)
    • Location (4)
  • Blog (6)

Because structures are ordered by lft by default, we can get a number corresponding to the entry's order in a structure by searching for entries in a section where its lft value is less than the reference entry.

{% set position = craft.entries
  .section('MySection')
  .andWhere('lft < "' ~ entry.lft ~ '"')
  .count() + 1
%}

This will result:

  • Home (1)
  • About (2)
    • Company (3)
    • Contact (4)
    • Location (5)
  • Blog (6)

Update: Seems the issue with positionedBefore() is a bug after all. I think I'll still leave this here in case someone's using a version of Craft without the fix? Not sure if Craft 2 has the bug or not.

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.