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.
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.
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
to12
so that the checkbox settingdisplay_blogname
appears below the "Site Title" input field. - We create a new control named
display_blogname
. We setpriority
to11
, which in our example is between the Site Title and Tagline input fields. - Set the
header_text
default color to#f44336
and thetransport
type topostMessage
. - We also created a new setting,
header_text_color
. Likewise, we'll also set the priority to11
so that it appears below theheader_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
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
操作掛鉤加載到定制器預(yù)覽窗口中。 customizer-control.js
文件將加載到定制程序后端,其中的設(shè)置和控制元素可通過 customize_controls_enqueue_scripts
操作掛鉤訪問。
下一步是什么?
WordPress 自成立以來一直在 PHP 方面進行了大量投資。因此,支持該生態(tài)系統(tǒng)的大多數(shù)開發(fā)人員對 PHP API 比 JavaScript API 更加熟練和熟悉也就不足為奇了。
直到最近,它才通過定制器和 WP-API 廣泛集成了 JavaScript。掌握 WordPress 定制器中的 JavaScript API 可能是一個相當大的挑戰(zhàn)。如前所述,WordPress 的這一面目前記錄最少。因此,我們將徹底討論這個主題。
同時,如果您正在尋找其他實用程序來幫助您構(gòu)建不斷增長的 WordPress 工具集,或者學(xué)習代碼并更加精通 WordPress,請不要忘記查看我們提供的內(nèi)容可在 Envato 市場購買。
在此,我們已準備好使用 WordPress JavaScript API 的所有基本元素。我們就到此結(jié)束。在本系列的下一部分中,我們將揭示 WordPress 中 JavaScript API 背后的更多內(nèi)容,并開始編寫可立即在主題中實現(xiàn)的功能腳本。
敬請期待!
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To roll back the WordPress version, you can use the plug-in or manually replace the core file and disable automatic updates. 1. Use WPDowngrade and other plug-ins to enter the target version number to automatically download and replace; 2. Manually download the old version of WordPress and replace wp-includes, wp-admin and other files through FTP, but retain wp-config.php and wp-content; 3. Add code in wp-config.php or use filters to disable core automatic updates to prevent further upgrades. Be sure to back up the website and database before operation to ensure safety and reliability. It is recommended to keep the latest version for security and functional support in the long term.

The steps to create a custom shortcode in WordPress are as follows: 1. Write a PHP function through functions.php file or custom plug-in; 2. Use add_shortcode() to bind the function to the shortcode tag; 3. Process parameters in the function and return the output content. For example, when creating button shortcodes, you can define color and link parameters for flexible configuration. When using it, you can insert a tag like [buttoncolor="red"url="https://example.com"] in the editor, and you can use do_shortcode() to model it

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

Object cache assists persistent storage, suitable for high access and low updates, tolerating short-term lost data. 1. Data suitable for "persistence" in cache includes user configuration, popular product information, etc., which can be restored from the database but can be accelerated by using cache. 2. Select a cache backend that supports persistence such as Redis, enable RDB or AOF mode, and configure a reasonable expiration policy, but it cannot replace the main database. 3. Set long TTL or never expired keys, adopt clear key name structure such as user:1001:profile, and update the cache synchronously when modifying data. 4. It can combine local and distributed caches to store small data locally and big data Redis to store big data and use it for recovery after restart, while paying attention to consistency and resource usage issues.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website
