How to sort blog posts by a custom field

Highlighted
Occasional Contributor

We ran into this issue where we wanted to sort items from a blog based on the contents of a custom field/module we added to that post type.

 

We noticed there are no solutions for this yet and discovered one that utilizes some undocumented features of Hubl. We're sharing it here for anyone else that might find it useful:

 

{# Detail Template -- Sorting Field #}
{% text 'sorting' label='Sorting Order #', no_wrapper=True, overrideable=True, export_to_template_context=True %}

{# Listing Template -- Sorting Logic #}
{% set post_list = blog_recent_posts('xxx', 999) %}
{% set post_list_sortable = [] %}
{% for post in post_list %}
    {# Assign the index as a fallback, un-ordered items appear below explicitly ordered ones #}
    {% set sort = post.widgets.sorting.body.value + 'x' + loop.index %}
    {% set tmp = post_list_sortable.append({ 'sorting': sort, 'record': post}) %}
{% endfor %}

{# Templating Output #}
{% for post in post_list_sortable|sort(false, false, 'sorting') %}
   {% set post = post.record %}
   <h2>{{post.title}}</h2>
{% endfor %}
2 Replies 2
Community Manager

Thank you for sharing @lformdesign!


Did my post help answer your query? Help the Community by marking it as a solution
Reply
0 Upvotes
Top Contributor | Platinum Partner

Great stuff - thanks for sharing!

Reply
0 Upvotes