How to create a select element option (drop-down) menu in the WordPress Theme Customizer

David Nash css, php, wordpress 2 Comments

I’m working on a project that requires the same basic theme for two companies that are both under the same group. The only real difference is the logo and theme colours.

Instead of creating two separate themes and having to maintain them separately I used WordPress “customize_register” action in the theme’s functions.php.

The official docs are here and very long and confusing. https://codex.wordpress.org/Theme_Customization_API

WordPress provides some basic types like a text field, image upload and colour picker, but no select menu: https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_control

Here’s the code I’m using to create a select element with two options (in the theme’s functions.php file):

Firstly, everything is wrapped inside add_action() – I’m using an anonymous function to group it all nicely.

Inside the function we create a new Class called Select_Control, which extends the basic WP_Customize_Control.

We give it a type and tell it how to render in wp-admin (under Appearance > Customize).

The $this->link() provides the name attribute for us.

Then inside each “option” we set the selected attribute if that’s what the value was previously set to.

We then call add_section to create a new section (similar to “Site Title”, “Navigation” in the theme customizer), create a setting, and then add that setting to the section in add_control.

To use this setting in the theme files, use:

For example in header.php I have this:

Which means that my body now also has class (eg) option_one … so in my CSS I can do:

Which means that when the colour scheme is set to the alternate option, I can override all the colours without having to spend time on anything else.

Simple! 🙂

Comments 2

  1. As background, let me tell you that I’m not a professional wordpress developer. I do this as a hobby for friends and I’m looking for ways to simplify their work. I’ve looked all around for something somewhat similar to what you have here. My goal is the following:
    1. Add a Control to the Background Image Section
    2. The Control should display a drop down menu
    3. The drop down would list a series of background images
    4. When the admin selects an item from the drop down, a corresponding image would be displayed as the new background, to be saved or not.
    Any assistance is appreciated. Thanks!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.