Today’s WordPress Wednesday was a inspired by a question on the WordPress Stack Exchange. Because of that, it may seem very specific, but it’s an issue other developers may very well run into while working with The Customizer API.
A Very Brief Intro to The Customizer
(Longer Intro to Come in a Later Post)
When a user goes to Appearance > Customize in WP Admin, they are opening The Customizer. It is basically a replacement for traditional theme options pages… But with a live preview on the right side of the screen. What’s super impressive is that the live preview is fully-functional, so users can navigate through the entire site in the preview.
If you are already familiar with The Customizer, you may have noticed that the controls/panels available change depending on what page is being viewed in the preview. For example, many themes use featured sections on the home page, but if you navigate to another page or post in the preview, the controls for the featured sections will disappear.
This happens because of the active_callback on the control, section, or panel. In our example, the active_callback would be is_front_page.
Example Using is_front_page
$wp_customize->add_section( 'rose_front_page_section', array( 'title' => 'Featured Boxes', 'description' => 'Edit the featured boxes on the home page.', 'priority' => 20, 'active_callback' => 'is_front_page', ) );
Using is_single as an active_callback in The Customizer
If you’re trying to have a control, section, or panel show on single blog posts only, there is a slight adjustment to make.
Because is_single takes an optional parameter, we have to make a wrapper function for our active_callback.
Here’s what that would look like:
// Our Wrapper Function function rose_callback_single() { return is_single(); } $wp_customize->add_section( 'rose_single_section', array( 'title' => 'Blog Post Layout', 'description' => 'Edit the layout of blog posts.', 'priority' => 20, 'active_callback' => 'rose_callback_single', ) );
Now, the “Blog Post Layout” section will only show in The Customizer when the preview is on a single post. You can even get creative with active_callbacks and make it so that different controls show depending on the value of another control. For example, a “Display Feature Boxes,” checkbox could show the “Feature Boxes” controls when checked. This helps de-clutter the admin experience for users.
Back to WordPress Stack Exchange
Unfortunately, the asker on the WP Stack Exchange had a separate issue with a JavaScript function and answered his own question with my solution + his other issue and selected it as “best answer.” But you can still up vote my answer, as his code would not have worked without it! 🙂
Thanks for reading this week! I hope you all have a great holiday!