Download
We're evolving to serve you better! This current forum has transitioned to read-only mode. For new discussions, support, and engagement, we've moved to GitHub Discussions.

Making custom helper; how does Publii order posts?

  • #7777
    Avatar photo[anonymous]

    I’m trying to make a custom helper that will link to the first and last posts in a listing of unknown length. (Specifically: the published unhidden post for which there are no previous posts, and the published unhidden post for which there are no later posts.)

    To make this work, I need to know: how does Publii determine which posts come before or after other posts in the listing? Like, they can be sorted in 8 different ways, so is there a sort-agnostic function that tells Publii how to order the posts, or is the sort type and direction hardcoded in?

    #7839
    Avatar photo[anonymous]

    Hi,
    Maybe you could use 2 helpers #getPostsByTags (https://getpublii.com/dev/getpostsbytags-helper/).

    {{#getPostsByTags “count=1&tag_as=id&tags=1,2,3&orderby=id&ordering=asc”}}
    <p>First post:</p>
    <h2>{{ title }}</h2>
    {{/getPostsByTags}}

    {{#getPostsByTags “count=1&tag_as=id&tags=1,2,3&orderby=id&ordering=desc”}}
    <p>Last post:</p>
    <h2>{{ title }}</h2>
    {{/getPostsByTags}}

    In this case the “tags” parameter creates the list of posts. Sorting is based on the post ID.
    If you don’t use the “allowed” parameter, hidden posts are excluded.

    #9035
    Avatar photo[anonymous]

    Apologies for coming back to this after six months but I only found out this ever got a response today.

    The reason I was trying to make a custom helper (or two of them, that’s not an issue) is that I want to be able to link to “the post that shows up first in the list” and “the post that shows up last in the list” regardless of what the sort option actually is—the goal is to switch how it behaves behind the scenes so for the non-techie intended user the experience is seamless.

    If said list was already sorted by ID, then a custom helper based off #getPostsByTags might work (I’m trying to calculate this for the entire site listing, not a specific tag, so out of the box it won’t work), but take this example of post IDs ordered by date: 5, 1, 2, 4, 3. So, posts 4 and 5 are backdated. For my use case this is extremely likely. If posts on the page are ordered by date, but the helper is ordering posts by ID, it will return the second post as “first” and the first post as “last”, which is erroneous. This is why I was asking for clarification on how Publii determines post order, so that I can use that to inform a helper that can check how posts are ordered and behave accordingly.