Table of Contents
Quick Start
Settings and Controls
Underlying code
Load JavaScript
下一步是什么?
Home Web Front-end JS Tutorial Getting Started: Understanding the WordPress Customizer JavaScript API

Getting Started: Understanding the WordPress Customizer JavaScript API

Sep 02, 2023 am 10:45 AM

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 );
	} );
} );
Copy after login

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' );
Copy after login

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. < /p>

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
Copy after login

Include the following code in customizer-preview.js.

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

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 );
Copy after login

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' );
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles