'Range over posts in nested section in hugo

I use this code to show related posts in the same sections for posts in /content/posts. However, the code stops working when I move the content to a nested section, such as content/posts/news, resulting in content from other sections appearing. Could anyone provide a solution or guide me on how to make this work?

{{ range where (where site.RegularPages "Section" .Section) "Permalink" "ne" .Permalink }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}


Solution 1:[1]

Try using .CurrentSection.Pages, which is better fit for this than filtering all the results from site.RegularPages.

Then the current page can also be filtered out with a simple where statement.

{{ range (where .CurrentSection.Pages "Permalink" "ne" .Permalink) }}
    <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1