Exclude pages in pagetree

On my current project, the customer wants to hide pages in the pagetree if they aren’t in the current language that the editors is editing. You have the option in EPiServer to use "Show only pages in [language]", but this isn’t persistent. So if you refresh the page you will lose this setting and have to set it again. Talked to EPiServer regarding if this was a bug or not, but got the answer that they had discussed this and it was by design. Therefore the customer came up with the requirement that this should not be necessary and wanted this by default since they aren’t going to translate the pages but instead have duplicate pages of English and Swedish pages.

This was quite an easy fix though. Since EPiServer uses REST queries to get children, you can create your own query when fetching children. Got the idea from Linus Ekström old blogpost

All you have to do is create a class, decorate it with [ServiceConfiguration(typeof(IContentQuery))] and make the class inherit from ContentQueryBase e.g. But there is an even easier way. EPiServer has a couple of classes that inherits ContentQueryBase, and there is one called GetChildrenQuery. So instead you can inherit from GetChildrenQuery, and therefore you will get the correct name at once and you can override the GetContent method to use default and modify it the way you want.

But since you’re registering another query with the same name, it won’t work until you give it a higher rank which is a property that will be checked, and it uses the one with highest rank. Default rank value is 0.

Below is my example where I’m only fetching pages in the language that is being edited. Note that this take place everywhere and not only in the pagetree, this also exclude blocks in other languages in the content asset panel.

 [ServiceConfiguration(typeof(IContentQuery))]
    public class ContentExcluder : GetChildrenQuery
    {
        public ContentExcluder(IContentQueryHelper queryHelper, IContentRepository contentRepository, LanguageSelectorFactory languageSelectorFactory) : base(queryHelper, contentRepository, languageSelectorFactory)
        {
        }

        protected override IEnumerable<IContent> GetContent(ContentQueryParameters parameters)
        {
            CultureInfo preferredCulture = ContentLanguage.PreferredCulture;

            List<IContent> content = base.GetContent(parameters).ToList();
          
            for (int i = 0; i < content.Count; i++)
            {
                var localizable = content[i] as ILocalizable;
                if (localizable != null && !localizable.Language.Equals(preferredCulture))
                {
                    content.RemoveAt(i);
                    i--;
                }
            }
            return content;
        }

        public override int Rank
        {
            get { return 100; }
        }
    }