1

I need to allow custom sorting of a channel entries loop, so I'm currently achieving this by using segments and URLs like this: mywebsite.com/products/sort/date/asc and mywebsite.com/products/sort/price/asc with the following code:

<ul>
  {exp:channel:entries channel="product" orderby="{segment_3}" sort="{segment_4}" pagination="bottom"}
    <li>{title}</li>
  {/exp:channel:entries}
</ul>

This works fine for ordering by date and other custom fields, but the downside is that the URLs can get a bit ugly as I need to add the custom field short name to the URL, e.g. mywebsite.com/products/sort/cf_product_ugly_custom_field/asc

My workaround has been to name the custom fields I wish to sort by from my usual format of {cf_product_price} to {price}, but this doesn't feel like an elegant solution.

Can anyone think of a more elegant way of doing custom sorting, without having to have the custom field in display in the URL like this? Thanks for any advice.

2

Stephen, simple conditionals are parsed before modules tags. Because of this, you can put them inside your opening channel:entries variables.

I put more custom fields on this example to make it more clear.

<ul>
  {exp:channel:entries channel="product"
    {if segment_3 == "price"}
    orderby="{cf_product_price}"
    {/if}
    {if segment_3 == "brand"}
    orderby="{cf_product_brand}"
    {/if}
    {if segment_3 == "foo"}
    orderby="{cf_product_foo}"
    {/if}
    {if segment_3 != "price"}{if segment_3 != "brand"}{if segment_3 != "foo"}
    orderby="{segment_3}"
    {/if}{/if}{/if}
    sort="{segment_4}"
    pagination="bottom"
  }
    <li>{title}</li>
  {/exp:channel:entries}
</ul>
2
  • Thanks Robson, this does what I need. :) As an aside, I just tried applying this to different site that was using Freebie, and I noticed that using "{freebie_x}" in the conditionals instead of segment_x didn't work. Is this likely to be a parse issue thing, so only works with simple conditionals with the native segment variables?
    – Stephen
    Jun 15 '13 at 3:32
  • 1
    Yes, just works with native segment variables! {freebie_X} is parsed together with all modules, so a conditional using it isn't a simple conditional.
    – Sobral
    Jun 15 '13 at 3:56

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.