search
HomeWeb Front-endJS TutorialGetting Started: Understanding the WordPress Customizer JavaScript API

The WordPress customizer has been actively developed since its inception. APIs are constantly evolving, including JavaScript APIs. However, it is one of the least documented APIs in the WordPress Codex. As a result, there are only a few detailed records showing how to actually exploit the JavaScript API.

Taking advantage of the JavaScript API in the WordPress Customizer actually allows us to provide a more compelling real-time experience when customizing a theme, rather than just casting changes from the control to the preview window.

You may be familiar with how to use the Customizer JavaScript API to cast changes to the preview window in real time. To do this, we set the transport mode to postMessage and add the corresponding JavaScript code as shown below.

wp.customize( 'blogname', function( value ) {
	value.bind( function( to ) {
		$( '.site-title a' ).text( to );
	} );
} );

However, we can also extend the API further, such as hiding, showing or moving parts, panels, controls, changing the value of a setting based on the value of another setting, and interconnecting previews and control interactions. These are what we will look at in this tutorial.

Quick Start

We’ve covered the WordPress Customizer quite extensively over several articles and series, covering the details of the Customizer API.

I think you have grasped the core concepts of the WordPress Customizer and components such as panels, sections, settings, and controls. Otherwise, I highly recommend you spend some time studying our tutorials and video courses on the topic before going any further.

  • WordPress Theme Customizer Guide
  • WordPress Theme Customizer
  • Writing a WordPress theme that can be used by customizers

Settings and Controls

First we will examine the Settings and Controls added in the Customizer for this tutorial. We'll also look at the code to put them in place.

起步:了解WordPress自定义器JavaScript API

In this tutorial, we will focus on the website "Site Title". As you can see above, we have two controls: the native WordPress “Site Title” input field and a custom checkbox to enable or disable the “Site Title”. These two controls are located in the Site Identification section. To the right of the image is a preview where you can see the "Site Title" being rendered.

Additionally, as you can see below, we have two controls located in the Colors section for changing the Site Title color and its hover status color.

起步:了解WordPress自定义器JavaScript API

Underlying code

Our theme is based on underscore, where all customizer related code is placed in the /inc/customizer.php file.

function tuts_customize_register( $wp_customize ) {

	$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';

	$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
	$wp_customize->get_control( 'blogdescription' )->priority = '12';

	$wp_customize->get_setting( 'header_textcolor' )->default = '#f44336';
	$wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage';

	// Checkbox to Display Blogname
	$wp_customize->add_setting( 'display_blogname', array(
		'transport' => 'postMessage',
	) );

	$wp_customize->add_control( 'display_blogname', array(
		'label'     => __( 'Display Site Title', 'tuts' ),
		'section'   => 'title_tagline',
		'type'      => 'checkbox',
		'priority'  => 11,
	) );

	// Add main text color setting and control.
	$wp_customize->add_setting( 'header_textcolor_hover', array(
		'default'           => '#C62828',
		'sanitize_callback' => 'sanitize_hex_color',
		'transport'         => 'postMessage',
	) );

	$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'header_textcolor_hover', array(
		'label'    => __( 'Header Text Color: Hover', 'tuts' ),
		'section'  => 'colors',
		'priority' => '11'
	) ) );
}
add_action( 'customize_register', 'tuts_customize_register' );

As you can see above, we made some modifications to the code to meet the needs of this tutorial.

  • We lowered the WordPress built-in setting blogdescription to 12 so that the checkbox setting display_blogname appears below the "Site Title" input field.
  • We create a new control named display_blogname. We set priority to 11, which in our example is between the Site Title and Tagline input fields.
  • Set the header_text default color to #f44336 and the transport type to postMessage.
  • We also created a new setting, header_text_color. Likewise, we'll also set the priority to 11 so that it appears below the header_textcolor setting.

All these settings are set via postMessage, not via refresh. The postMessage option allows values ​​to be transferred asynchronously and displayed in the preview window in real time. However, we also have to write our own JavaScript to handle the changes.

Load JavaScript

We need to create two JavaScript files: one file customizer-preview.js to handle the preview, and another file customizer-control.js to handle the inside of the customizer panel of controls.

js
├── customizer-preview.js // 1. File to handle the Preview
├── customizer-control.js // 2. File to handle the Controls
├── navigation.js
└── skip-link-focus-fix.js

Include the following code in customizer-preview.js.

( function( $ ) {
	// Codes here.
} )( jQuery );

It is currently an empty enclosing JavaScript function. We'll discuss more specifically how to preview changes in the preview window in the next tutorial in this series.

In another file customizer-control.js, we add the following code:

(function( $ ) {
	wp.customize.bind( 'ready', function() {
		var customize = this;
		// Codes here
	} );
})( jQuery );

As you can see above, we will wrap this code in this file in the customizer ready event. This will ensure that everything in the customizer, including settings, panels, and controls, is completely ready before we start executing any custom functionality.

Finally, after adding the code, we will load these two JavaScript files in two different locations.

// 1. customizer-preview.js
function tuts_customize_preview_js() {
	wp_enqueue_script( 'tuts_customizer_preview', get_template_directory_uri() . '/js/customizer-preview.js', array( 'customize-preview' ), null, true );
}
add_action( 'customize_preview_init', 'tuts_customize_preview_js' );

// 2. customizer-control.js
function tuts_customize_control_js() {
	wp_enqueue_script( 'tuts_customizer_control', get_template_directory_uri() . '/js/customizer-control.js', array( 'customize-controls', 'jquery' ), null, true );
}
add_action( 'customize_controls_enqueue_scripts', 'tuts_customize_control_js' );

customizer-preview.js 文件将通过 customize_preview_init 操作挂钩加载到定制器预览窗口中。 customizer-control.js 文件将加载到定制程序后端,其中的设置和控制元素可通过 customize_controls_enqueue_scripts 操作挂钩访问。

下一步是什么?

WordPress 自成立以来一直在 PHP 方面进行了大量投资。因此,支持该生态系统的大多数开发人员对 PHP API 比 JavaScript API 更加熟练和熟悉也就不足为奇了。

直到最近,它才通过定制器和 WP-API 广泛集成了 JavaScript。掌握 WordPress 定制器中的 JavaScript API 可能是一个相当大的挑战。如前所述,WordPress 的这一面目前记录最少。因此,我们将彻底讨论这个主题。

同时,如果您正在寻找其他实用程序来帮助您构建不断增长的 WordPress 工具集,或者学习代码并更加精通 WordPress,请不要忘记查看我们提供的内容可在 Envato 市场购买。

在此,我们已准备好使用 WordPress JavaScript API 的所有基本元素。我们就到此结束。在本系列的下一部分中,我们将揭示 WordPress 中 JavaScript API 背后的更多内容,并开始编写可立即在主题中实现的功能脚本。

敬请期待!

The above is the detailed content of Getting Started: Understanding the WordPress Customizer JavaScript API. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment