Add a Page Select to the Customizer

I’ve been working on a new theme that allows users to select certain pages in the customizer, and then display those pages out on a “showcase” template. I think this is pretty useful functionality and wanted to share how I implemented it.

Add Settings, Controls and Sanitization

First, we’ll need to the page select boxes to the customizer. In the code below, I add a new customizer section called “Showcase”. Then, I loop through the add_setting / add_control functionality in order to display four distinct page select boxes.

I’ve also created a function called “prefix_get_pages_array” which returns an array of all the pages to be used both by the controls and the sanitization function. You’ll notice it sorts the pages alphabetically, and indents sub-pages slightly with an em dash when output in the select box.

Finally, I have a sanitization function which makes sure the selected page is actually a valid choice. Here’s what that all looks like:

Display Page Selections in a Template

I’ve seen various ways of outputting pages based on selections, but I like my method because it uses a single query and sorts pages based on the order they were selected.

Here’s what that looks like:

You may have noticed that a message is displayed to users who have the ability to customize if no pages are selected. This also links to that section in the customizer.

Advanced

I’d love to continue working on this in order have the amount of pages selected dynamic. i.e. Just click “Add Page” and you get another select box to use. If anyone has built something like this out, definitely let me know.

About Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Nano. Find me on twitter @devinsays.

7 Responses

      1. Personally, I’d just roll with an absint() call to sanitize the data. But, if you need to validate it against a whitelist, get_post_status() would work (plus, you could actually test that it’s published using that). I think that’s overkill in this scenario though.

  1. As Justin suggested, I would just use the built-in dropdown-pages option if possible. You’ll probably have to roll your own if you end up doing something like dynamically adding selects, but it should do for standard page selection.

Leave a Reply