How to sort blog posts by a custom field

lformdesign
Participant

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 %}
3 Replies 3
jennysowyrda
Community Manager

Thank you for sharing @lformdesign!


We are excited to announce that the Community will be launching a weekly newsletter on November 2, 2020!
Sign up today!
0 Upvotes
bschneidewind
Top Contributor | Diamond Partner

Great stuff - thanks for sharing!

0 Upvotes
crowell-tailord
Participant

Not sure if this is newer code functionality than your original post, but this is how we got around to doing it --

 

The widgets.module_XX.body.event_countdown.start_date_time is a custom field we use for defining an Event's start date. 

 

{% for content in contents|sort(false, false, 'widgets.module_1587729346876105.body.event_countdown.start_date_time') %}
0 Upvotes