Trying to filterBy multiple tags

Post #1 has: tag1, tag2
Post #2 has: tag1
Post #3 has: tag2

$posts = $posts->filterBy('tags', 'in', $block->postsTags()->split(','));

postsTags() is a tags field where I’ve entered tag1 and tag2.

Post #2 and Post #3

Why isn’t Post #1 among the result? :thinking:

Using toArray() instead of split() and the result is just Post #1, now how do I get all of them :upside_down_face:

Your code works for all post that have only one tag. But here we need to compare arrays:

$blockPostTags = $block->postsTags()->split(',');
$posts = $posts->filter(function($post) use($blockPostTags) {
  return count(array_intersect($post->tags()->split(','), $blockPostTags)) > 0;
1 Like

Awesome! Thanks!

This will also work and is less code:

$posts = $posts->filterBy('tags', 'in', $block->postsTags()->split(','), ',');

Note the fourth parameter.

1 Like

Ah thanks, that works too :raised_hands: :raised_hands:

The first example is still useful if you want to only get siblings with a "stronger relationship, if you adapt it like in the example I just added to the filtering compendium:

1 Like