


Enhance your WordPress theme: Introduce new settings with the theme customizer
Sep 03, 2023 pm 10:17 PMSo far, we have learned what a theme customizer is, how it works, and its unique components. We even discussed how to serialize the options into a database so we can retrieve them later when working with the theme.
To do this, it’s time for us to start working on our own using the theme customizer. In this article, we’ll look at transfers, how they work, and the differences between their two main methods.
Additionally, we will introduce our own control into one of the existing parts of WordPress and see how it works with various transport models.
Everything about transportation
Another concept we need to be familiar with before we actually write any code is the concept of transport
s. Essentially, this is how the theme customizer sends data to the theme to display changes.
There are two ways of data transmission:
-
refresh
- This is the default method. Using this method, when the user changes settings in the theme customizer, the frame displaying the theme will refresh before showing the changes. -
postMessage
- This method must be explicitly stated, but it provides a more enhanced user experience. When using this method, an asynchronous request is made and the theme's appearance is updated to reflect the user's settings without reloading the page.
The concept is simple, right?
In this article, we will implement two versions of the new theme customization settings. First, we'll cover a setup using the refresh
transport. Afterwards, we'll improve the setup to use the postMessage
transport.
At the end of the article I will link to both versions of the code so that you can download and install something on your local machine without simply referring to this article.
With that being said, let’s get started.
Implementing our new settings
In this article, we will introduce a setting that allows users to change the color of all anchors present in their theme. We rarely need to change the color of anchors universally across our entire site, but implementing this specific setup will teach you the following:
- How to implement new settings in an existing section
- How to use
WP_Customize_Color_Control
- How to use the
refresh
transmission method and how to use thepostMessage
transmission method
Clearly, there is still a lot of work to be done.
Add our hook
First, let's add an anchor to the index.php template so we can actually color it. This is a simple change. Just make sure your index.php template contains the following:
<div id="content"> This is the content. <a href="#">This is an anchor</a> so that we can tell the Theme Customizer is working. </div><!-- /#content -->
Next, we need to introduce a function that hooks into the customize_register
operation:
function tcx_register_theme_customizer( $wp_customize ) { // More to come... } add_action( 'customize_register', 'tcx_register_theme_customizer' );
Here we define a function that introduces our new setup. Note that the most important thing about this function is that it accepts a single parameter - wp_customize
- which allows us to add our sections, settings, and controls to the theme customizer.
Recall from the previous article, we mentioned that WordPress provides many sections so we don’t have to add our own. In this example, we will utilize the predefined colors
section.
Implementation settings
In the context of the tcx_register_theme_customizer
function, add the following code block:
$wp_customize->add_setting( 'tcx_link_color', array( 'default' => '#000000' ) );
This means we are introducing a new setting to the customizer with the ID tcx_link_color
and the default color is black.
This will come into play when we implement the color picker. So let's get started now. After the above code block, add the following block to your function:
$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'link_color', array( 'label' => __( 'Link Color', 'tcx' ), 'section' => 'colors', 'settings' => 'tcx_link_color' ) ) );
This will introduce a color picker control in the colors
section. It will add an internationalization tag with the content "Link Color" and bind itself to the tcx_link_color
setting we defined in the first snippet above.
The final version of the function should look like this:
function tcx_register_theme_customizer( $wp_customize ) { $wp_customize->add_setting( 'tcx_link_color', array( 'default' => '#000000' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'link_color', array( 'label' => __( 'Link Color', 'tcx' ), 'section' => 'colors', 'settings' => 'tcx_link_color' ) ) ); } add_action( 'customize_register', 'tcx_register_theme_customizer' );
Demo Control
At this point, save your work, launch WordPress, navigate to the theme customizer, and you should see the following:
Note that you can expand the color picker, select a color, and generally use it as expected; however, the content's anchor point does not change at all. Next, we add the following functions to the functions.php file.
function tcx_customizer_css() { ?> <style type="text/css"> a { color: <?php echo get_theme_mod( 'tcx_link_color' ); ?>; } </style> <?php } add_action( 'wp_head', 'tcx_customizer_css' );
Obviously, this function is hooked into the wp_head
operation. It is responsible for reading the value corresponding to our new setting (identified by tcx_link_color
) from the options table and then writing that value into the style
block in the page header.
Once done, refresh the theme customizer and you should notice a change whenever you select a color. You should also notice that the page will flicker whenever you change the colors as well as the title, tagline, or static homepage options.
更新我們的交通
現(xiàn)在我們已經(jīng)完成了這項工作,我們可以引入一些更改,這些更改將改善用戶體驗,因為它涉及使用 WordPress 主題定制器更改主題選項。
首先,我們需要更新 footer.php 模板,使其包含對 wp_footer()
的調(diào)用。這樣我們就可以在主題的頁腳中加載 JavaScript,這是 postMessage
傳輸所必需的。
頁腳應(yīng)如下所示:
<div id="footer"> © <?php echo date( 'Y' ); ?> <?php bloginfo( 'title' ); ?> All Rights Reserved </div><!-- /#footer --> <?php wp_footer(); ?> </body> </html>
接下來,我們需要更新 functions.php 中的 add_setting
調(diào)用,以便它使用正確的傳輸方法。
更新代碼,使其看起來像這樣:
$wp_customize->add_setting( 'tcx_link_color', array( 'default' => '#000000', 'transport' => 'postMessage' ) );
最后,不要刪除我們在上一個版本中定義的函數(shù) tcx_customizer_css
,因為它仍然需要讀取我們?yōu)殄^點選擇的值 - 我們只是異步保存它們而不是刷新時保存。
現(xiàn)在在主題的根目錄中創(chuàng)建一個名為 js 的目錄,然后將 theme-customizer.js 文件添加到該目錄中。
在此 JavaScript 文件中,我們需要添加以下代碼塊。通常,我喜歡嘗試解釋我們正在做的事情,但在這種情況下,在顯示代碼之后檢查會更容易。
(function( $ ) { "use strict"; wp.customize( 'tcx_link_color', function( value ) { value.bind( function( to ) { $( 'a' ).css( 'color', to ); } ); }); })( jQuery );
在這段代碼中,請注意,我們可以訪問 wp
JavaScript 對象,該對象為我們提供 customize
消息,就像服務(wù)器端 $wp_customize->add_setting()
的設(shè)置一樣。
接下來,請注意該函數(shù)接受設(shè)置的 ID,這是一個回調(diào)函數(shù),該函數(shù)接收具有原始值的對象,然后允許我們將另一個函數(shù)綁定到該對象以進行更改每當(dāng)該對象發(fā)生更改時。
還在我身邊嗎?
另一種說法是:當(dāng)鏈接顏色更改時,只要使用顏色選擇器,我們就可以更改主題的顯示。
話雖如此,讓我們重新訪問 functions.php 文件并引入一個新函數(shù),以便我們可以正確地將 JavaScript 文件排入隊列。
首先,我們將引入一個名為 tcx_customizer_live_preview()
的函數(shù),它將掛鉤 customize_preview_init
操作:
function tcx_customizer_live_preview() { // More to come } add_action( 'customize_preview_init', 'tcx_customizer_live_preview' );
接下來,我們將對 wp_enqueue_script
進行標(biāo)準(zhǔn)調(diào)用,這將引入我們的 theme-customizer.js 文件,但請注意,我們將最后一個參數(shù)作為 true
傳遞,因此該腳本已添加到文檔的頁腳:
wp_enqueue_script( 'tcx-theme-customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'jquery', 'customize-preview' ), '0.3.0', true );
該函數(shù)的最終版本如下所示:
function tcx_customizer_live_preview() { wp_enqueue_script( 'tcx-theme-customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'jquery', 'customize-preview' ), '0.3.0', true ); } add_action( 'customize_preview_init', 'tcx_customizer_live_preview' );
保存您的所有工作。假設(shè)您已正確完成所有操作,您現(xiàn)在應(yīng)該能夠更改標(biāo)題、標(biāo)語、鏈接顏色和靜態(tài)首頁選項,無需刷新頁面。
更好的用戶體驗,是嗎?
但還有更多......
我們在本文中查看了很多。以至于本文的源代碼已發(fā)布為兩個不同的下載:
- 首先,下載使用
refresh
傳輸?shù)陌姹?/li> - 然后,下載使用
postMessage
傳輸?shù)陌姹?/li>
但是我們還沒有完成。在下一篇文章中,我們將了解如何引入我們自己的原創(chuàng)部分以及我們自己的原創(chuàng)設(shè)置和控件來完善本系列。
現(xiàn)在,請嘗試使用我們上面提供的代碼,以便為下一篇文章的工作做好準(zhǔn)備!
The above is the detailed content of Enhance your WordPress theme: Introduce new settings with the theme 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
