Change title of customize section

When creating a customize section, you define a title for it. Sometimes it can be useful to change this title during a customize session, for example, to reflect the value of a control, like the GIF shows:

A GIF showing the detail view of a section. When changing a select field, the section title is also updated.

I did not find a solution for that via the Customize JS API, so there was only the way via manipulating the DOM directly.

We can reach the title of a section in the detail view (like shown in the GIF) as follows:

document.querySelector('#sub-accordion-section-sectionId .customize-section-title h3').lastChild.textContent

And the section title in the panel view like that:

document.querySelector('#accordion-section-sectionId .accordion-section-title').childNodes[0].textContent

To get the behavior from the GIF, we use the following code:

;(function (api) {
	api.bind('ready', function () {
		// Listen to changes of the page control value to update the page title in the section head and section title.
		api.control('portfolio_category_page[1][id]', function (control) {
			control.setting.bind(function () {
				var sectionTitle= 'No page selected';

				// Build the title for the section.
				if ('0' !== api.control('portfolio_category_page[1][id]').setting.get() && '' !== api.control('portfolio_category_page[1][id]').setting.get()) {
					// Get the page title.
					var pageSelectElem = document.querySelector('#customize-control-portfolio_category_page-1-id select');
					if (-1 !== pageSelectElem.selectedIndex) {
						sectionTitle= '»' + pageSelectElem.options[pageSelectElem.selectedIndex].text.trim() + '«';
					}
				}

				// Add the page title to the section.
				document.querySelector('#accordion-section-hannover_portfolio_category_page_section\\[1\\] .accordion-section-title').childNodes[0].textContent = sectionTitle;
				document.querySelector('#sub-accordion-section-hannover_portfolio_category_page_section\\[1\\] .customize-section-title h3').lastChild.textContent = sectionTitle;
			});
		});
	});
})(wp.customize);

We listen to changes of the portfolio_category_page[1][id] control’s setting. If it changes we check if the »empty« select value is selected or a page (we can get the currently selected value of a select element via selectedIndex). If a page is selected, we save its title in a variable and set it as the value for both occurrences of the section title.

Related posts

Leave a Comment

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