Sorting pages in a Wagtail PageChooserPanel dialog

Is it possible to explicitly order the list of pages based on some attribute (e.g. page.specific.popularity) in a Wagtail PageChooserPanel? http://docs.wagtail.io/en/v2.0/reference/pages/panels.html does not mention this as possibility, and I can't find anything else in the docs that hints at how one might make this happen.

Upvotes: 1

Views: 532

Answers (1)

LB Ben Johnston
LB Ben Johnston

Reputation: 5186

Yes, there is a hook called construct_page_chooser_queryset that allows you to modify the pages results that get shown in the page chooser modal.

Example Code

This would be in your wagtal_hooks.py file, example based on docs linked above.

from wagtail.core import hooks

@hooks.register('construct_page_chooser_queryset')
def order_pages_in_chooser(pages, request):
    if "choose-page" in request.path:
        # showing page in a page chooser modal
        return pages.order_by('?')  # order randomly

    # search results shown in admin/pages/search - return in default order
    return pages

Upvotes: 2

Related Questions