Sort a collection by taxonomy terms then show all sorted by date in a single loop? #6099
Replies: 2 comments 1 reply
-
Why are you sorting twice, you said show all that have a term then sort by date? |
Beta Was this translation helpful? Give feedback.
-
A quick way to accomplish this would be to create a custom modifier that returns the number of items in common between the entry's terms and the page's terms (does not handle the case if any value is <?php
namespace App\Modifiers;
use Statamic\Modifiers\Modifier;
class IntersectionCount extends Modifier
{
public function index($value, $params, $context)
{
// Assumes both the value and param will be an OrderedQueryBuilder
// that contains a TermQueryBuilder inside.
return collect($value->get()->all())->pluck('slug')
->intersect(collect($params[0]->get()->all())->pluck('slug'))
->count();
}
} We can then use {{ collection:blog :id:not="id" limit="3" sort="date:desc" as="entries" }}
{{ blog_posts = entries orderby (
(x => x.tags | intersection_count(page:tags)) 'desc',
(x => x.date) 'desc') }}
{{ title }}<br />
{{ /blog_posts }}
{{ /collection:blog }}
With the modifier and the ordering on two columns, all entries that have terms in common with the current page will appear first in the list. Any items that do not have terms in common will appear at the end, with a maximum of 3 total entries displayed. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a way to sort a collection to show entries that include the same taxonomy term then show all sorted by date? (With a limit of 3)
Right now I've got a if conditional that does this separately but I reckon it's more performant to do it in a single loop. Perhaps this is possible with the new antlers parser (which I'm using but still very new to) where I could build an array locally using my desired filters and sorting?
Here's my double loop with conditional (and
total_items
used to limit the return to 3 entries):I was thinking maybe something like this below but every variation I try doesn't work:
Beta Was this translation helpful? Give feedback.
All reactions