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.
Instead of using
select
for the customizer controltype
argument, you can usedropdown-pages
and not have to roll your ownchoices
array. It’ll cut back on some of the code.Thanks Justin, I had forgotten about that control!
One benefit of manually creating the array is that you can also use it to do the sanitization. How do you do that without pulling the array of pages?
I looks like “get_post_status” might be a good option. Found that referenced in this article: https://tommcfarlin.com/wordpress-post-exists-by-id
A less strict sanitization could just check if the ID is an intval.
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.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.
Thanks Justin and Mike! Example code has been updated.
Hi, great article.
Sorry for my newbie question, but what “priority” means here?
Where this number come from?
Priority determines the order in the customizer. Here’s some more details: https://wptheming.com/2012/06/add-options-to-theme-customizer-default-sections/