Table of Contents
Quick Start
Settings and Controls
Underlying code
Load JavaScript
下一步是什么?
Home CMS Tutorial WordPress Getting Started with the JavaScript API in the WordPress Customizer

Getting Started with the JavaScript API in the WordPress Customizer

Sep 03, 2023 pm 11:13 PM

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 with the JavaScript API in the WordPress Customizer. 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)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles