Table of Contents
Why introduce new classes?
How to use this media control
Basic Usage
More options
Retrieve saved settings
Home CMS Tutorial WordPress Using the WordPress Theme Customizer Media Controls

Using the WordPress Theme Customizer Media Controls

Feb 15, 2025 am 10:29 AM

Using the WordPress Theme Customizer Media Controls

Detailed explanation of WordPress Theme Customizer Media Control: New WP_Customize_Media_Control Class

Recent WordPress updates have changed its API. Some functions and classes are added, others are deprecated. This article discusses topic customizer media controls. In previous versions, these controls were available, but only in the WP_Customize_Upload_Control class. Now we have discovered a new class to manage media called WP_Customize_Media_Control.

First, I will explain how to use this new class to manage media controls in the theme customizer. We will then introduce a concrete class example that extends WP_Customize_Media_Control to allow control of cropping images.

Key points:

  • WordPress Theme Customizer Media Control has been updated to include new functions and classes, including new WP_Customize_Media_Control classes, which allows for better media management.
  • WP_Customize_Media_Control Can be used to allow the user to select an audio file that is accessible on all pages. This control can be added to the theme's functions.php file or to a new plug-in.
  • WP_Customize_Media_Control can be extended to add more features, such as the WP_Customize_Cropped_Image_Control class, which allows users to select and crop images before using them.
  • The new control makes the theme customizer more versatile, allowing developers to add their own media controls and retrieve the most useful value: Media ID. This base class can be extended to more specific controls.

New Base Class for Managing Media Controls

Why introduce new classes?

Before version 4.3, WordPress provided us with WP_Customize_Upload_Control, a class that manages media file uploads in the theme customizer. However, this class does not save the uploaded media ID, but only its URL. Since ID is the more common way to retrieve information about media files, it was decided to provide a new class WP_Customize_Media_Control.

If you are used to using WP_Customize_Upload_Control, you can still use it without any problems, as it now extends the WP_Customize_Media_Control class, thus ensuring compatibility. However, updating your code and using WP_Customize_Media_Control is definitely a better idea.

How to use this media control

This new media control is used the same way as its predecessor, except for the saved values. Since it is no longer a URL, it cannot be cleaned up in the same way.

To understand how to use this control, we will review a specific example. We will see how to get users to select an audio file that visitors can listen to on all pages. You can write code to a functions.php file of the topic or into a new plug-in. Both are acceptable, and both options have their own advantages.

Note that since the Topic Customizer API is not the main focus of this article, I will not describe all the available options for the functions we will call here.

Basic Usage

First, we start with a WordPress function that will be called by WordPress when the user wants to display the theme customizer. This function will add our custom elements to this customizer. To inform WordPress that we want it to call our function at the right time, we use the customize_register action.

function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');
The

parameter (named here $wp_customize) is an object representing the theme customizer. It contains all the methods you need to add settings.

Since there is no default section that is really suitable for adding our custom sound, we will add our own section, simply named "Sound".

$wp_customize->add_section('sound', array(
    'title' => 'Sound',
    'description' => 'Add a sound to your website',
    'capability' => 'edit_theme_options'
));

As expected, this method creates a new section called "Sound". When the user opens it, they will see the instructions at the top. Due to the third option, this section can only be seen by users who can already edit the topic options. Finally, note the first parameter before the array option: it defines the ID of the section, which we must reuse when we want to add a control in this section.

If you open the theme customizer now, you won't see this section. This is normal: WordPress does not display the empty part, so to see it we have to fill it with at least one control.

Theme Customizer API divides the control into two parts: a UI control that allows the user to select or type the correct data, and a setting that retrieves the current value and saves the new value. Treat settings as an interface between the UI control and the database.

We need to create settings before creating the control.

$wp_customize->add_setting('music', array(
    'type' => 'theme_mod',
    'capability' => 'edit_theme_options',
    'sanitize_callback' => 'absint'
));

We specify "music" as the ID we set. It is a theme modification as shown in the first option. The capability option is the same as the add_section() method. Finally, we specify absint() as the cleanup callback function. This WordPress function is a shortcut to abs(intval()) to ensure that the value is a positive integer. As we saw above, WP_Customize_Media_Control will store an ID, so it is exactly the function we want to use to clean up the values.

We are now ready to add UI controls that users can see.

$wp_customize->add_control(new WP_Customize_Media_Control($wp_customize, 'music', array(
    'section' => 'sound',
    'label' => 'Music',
    'mime_type' => 'audio'
)));

To build the WP_Customize_Media_Control object, three parameters are required: the current theme customizer instance, the corresponding set ID (we just created above), and an option array.

The

section option is used to indicate the part we want to place the control. We are here using the sections we created specifically for this purpose. Then we indicate the label of the field. You can place any value you want here.

Finally, here we will provide users with a way to select media files. Since we want them to have only select audio files, we specify the audio as the desired MIME type. This way, WordPress will not allow other types of files to be selected.

This is all about creating the control. Now you can open the Theme Customizer: You should see our sections and our controls.

More options

Note that the array of options we provide as the third parameter of the WP_Customize_Media_Control constructor can accept more options.

In addition to its tags, you can also display more information about the control through the description option. In fact, by providing a non-empty string for the description option, you can display instructions below the label, for example, describing where it will be displayed.

You can set its priority through the priority option. This number defines the order in which objects must be displayed. By default, priority is set to 10 and objects are displayed in the order in which they are created. But you can change it. For example, if you create two objects, you can set the priority of the first object to 10 and the priority of the second object to 0: this way, the second object will be displayed first. This option may be useful if your plugin or theme provides multiple controls that must be displayed in a specific order.

Retrieve saved settings

To retrieve the settings saved by the user, we will create a new function called echo_theme_sound(). This function will be called where you want to display in the topic to display the audio tags corresponding to the selected media.

First of all, remember that our settings are a theme modification, so to retrieve its value we have to use the get_theme_mod() function.

function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');

If the user has made a selection, this variable will contain the ID of the selected media. In other words, to check if a choice has been made, we just need to check if this ID is different from zero.

$wp_customize->add_section('sound', array(
    'title' => 'Sound',
    'description' => 'Add a sound to your website',
    'capability' => 'edit_theme_options'
));

To build an audio tag, we will use wp_audio_shortcode(), which requires a parameter: an array of options that will actually be the attribute of the tag.

This array must contain an option named src which is the URL of the audio file. To retrieve this URL, we can use wp_get_attachment_url() and the ID retrieved earlier. If you want to use other properties you can, but not mandatory. For more information about available properties, see WordPress Codex.

We are now ready to display our audio tags. I'm here to wrap it into a div, but you can choose another tag and another style. You can even, for example, define two parameters echo_theme_sound() and $before for your $after function to allow the user to provide text displayed before and after the audio tag.

function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');

Now, just call the echo_theme_sound() function wherever you want and enjoy the result! Note that once you use this function in a theme file, you can see the changes you made in the theme customizer directly after making the changes without refreshing the page.

Manage cropped images

can be extended WP_Customize_Media_Control to add more features. If you need a specific example of what features can be added like this, you can find one in WordPress Core itself, using the WP_Customize_Cropped_Image_Control class.

As you guessed from its name, this is useful when you want to provide a way for the user to select and crop an image before using it.

Here, we will use it to add a subtitle image to the current default WordPress theme (Twenty Fifteen). I chose to show this image at the top of the title, just above the website title, but, again, you can put it as you like: the goal of this article is just to show a specific example of the new API.

First, we create our settings. Since we will store the media ID, this setting is basically the same as the audio tags added earlier.

$wp_customize->add_section('sound', array(
    'title' => 'Sound',
    'description' => 'Add a sound to your website',
    'capability' => 'edit_theme_options'
));

Then, the interesting part: the control itself. Like the WP_Customize_Media_Control, the constructor of WP_Customize_Cropped_Image_Control requires three parameters, which are exactly the same: the theme customizer instance, the set ID, and an array of options.

$wp_customize->add_setting('music', array(
    'type' => 'theme_mod',
    'capability' => 'edit_theme_options',
    'sanitize_callback' => 'absint'
));

Here, I did not create a new section: we reuse the part that WordPress has already used to provide the controls, allowing the user to select the background image title. The label option is an already known option and you will be more interested in two other options: width and height.

These options are used to control the size of the final image. The user selects the image they want, and then a graphics tool allows them to crop the image they want. WordPress will crop the image based on this selection and resize the cropped image to the size you selected with these options.

When users crop an image, the constraints of the image proportions are here, and they cannot select a portion of the image with other proportions. But this can change.

In fact, this class offers two other options: flex_width and flex_height. By default, both options are set to false, and the aspect ratio given by the dimensions you indicate is a constraint: the user must select an area with the same proportion.

However, if you set one of the options to true, this constraint will be removed and the user will be able to select a portion of the image with any scale. Note that WordPress will still resize the results to the size you request, so it may deform.

When using flex_width and flex_height, the ratio is important. In fact, at the beginning, WordPress provides users with a default crop area. This area corresponds to the largest available area in the image with the desired scale (such as the maximum possible square in a rectangle). This will give us what we are talking about here the default width and height.

If flex_width is set to false, the user will not be able to select areas larger than the default width. If you set this option to true, this constraint will be cancelled. The same can be said for flex_height.

Lastly, if flex_width and flex_height are set to false (their default values), and if the user selects an image that is exactly the same size as you indicated in the width and height options, the cropping step will be skipped.

Note that cropping images does not change the original image: a new submedia will be created with the cropped image and the original file remains the same. This way, if your users need to use the same image in multiple places, they don't have to upload the same image multiple times.

The method of retrieving cropped images is similar to the method we used to retrieve sounds before: we use get_theme_mod() to get the image ID and wp_get_attachment_url() to get its URL. Then we display it the way we want it to. Here I chose the easiest way to echo the image.

function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');

Conclusion

With these new controls, theme customizers are becoming more and more interesting as it allows developers to do more easily. Now, if you need a media control in this customizer, you can add your own control and retrieve the most useful value: Media ID.

The base class seen in this article can be extended when you need more specific controls. This is done in multiple places in the WordPress core: the crop image control extends WP_Customize_Media_Control, and this class itself is extended by the control used by the new site icon API. These are just examples of actions you can do with this API.

You can use the theme or plug-in to use the theme customizer. However, since it's more practical for me to provide a small plugin, you can find one via this link. It combines the examples seen in this article.

(The FAQ section should be inserted here, and the content is consistent with the FAQ part in the input text)

The above is the detailed content of Using the WordPress Theme Customizer Media Controls. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1525
276
How to update plugins using WP-CLI How to update plugins using WP-CLI Jul 20, 2025 am 01:07 AM

Updating plug-ins using WP-CLI requires 1. Log in to the server through SSH and enter the website directory; 2. Execute wppluginupdateplugin-slug to update a single plug-in or wppluginupdate--all to update all plug-ins; 3. Check permissions, disk space and conflicting plug-ins when encountering problems. There is no need to log in to the background throughout the process, but you need to pay attention to the backup and compatibility risks, and you can assist in troubleshooting problems through --dry-run or --debug parameters.

How to manage cron jobs with WP-CLI How to manage cron jobs with WP-CLI Jul 21, 2025 am 12:50 AM

TomanagecronjobsinWordPressusingWP-CLI,youcanlist,run,schedule,anddeleteeventsviacommand-linetools.1.Usewpcroneventlisttocheckactivecroneventsandfilterwith--hook=some_hook_name.2.Manuallytriggerataskwithwpcroneventrunsome_hook_name.3.Schedulenewtasks

How to escape and sanitize data in WordPress How to escape and sanitize data in WordPress Jul 21, 2025 am 12:17 AM

Data escape and disinfection are two key steps in WordPress security development. 1. Data disinfection (Sanitize) is used for safe storage and is processed before saving user input, such as using functions such as sanitize_text_field() and sanitize_email() to clean up data; 2. Data escape (Escape) is used for safe display, and is processed when output to the front end, such as using functions such as esc_html() and esc_url() to prevent script execution; 3. Use appropriate hooks and function libraries, such as wp_kses_post() to filter rich text content, add_query_arg() to safely operate URL parameters; 4. Pay attention to different scenarios

How to migrate a multisite site to a single site How to migrate a multisite site to a single site Jul 19, 2025 am 12:18 AM

To migrate subsites in WordPress multi-site to a single site, you need to perform the following steps in turn: 1. Use WordPress's own export tool to export articles, pages, etc.; 2. Export the table with the corresponding prefix from the database and rename it to a single-site format, and replace the old domain name at the same time; 3. Manually migrate media files and repair paths; 4. Configure the themes, plug-ins and settings of the new site and conduct tests. The entire process requires attention to data cleaning, URL replacement and plug-in compatibility to ensure normal functions after migration.

How to store plugin options in WordPress How to store plugin options in WordPress Jul 27, 2025 am 12:29 AM

In WordPress plug-in development, the recommended way to correctly store plug-in options is to use register_setting() combined with get_option() and update_option(). First, register the setting item through register_setting('section','option_name'); second, use update_option('option_name',$value) to save the data when submitting the form; again, use get_option('option_name','default_value') to get the value when loading the page; in addition, it is recommended to merge multiple fields.

How to exclude categories from the loop How to exclude categories from the loop Aug 07, 2025 am 08:45 AM

There are three ways to exclude specific categories in WordPress: use query_posts(), use the pre_get_posts hook, or use the plug-in. First, use query_posts() to directly modify the main loop query in the template file, such as query_posts(array('category__not_in'=>array(3,5))), which is suitable for temporary adjustment but may affect paging; second, it is safer to add functions in functions.php through the pre_get_posts hook. For example, excluding the specified classification ID when judging the home page main loop, it will not affect other page logic; finally, WPCate can be used

How to create custom page templates How to create custom page templates Jul 21, 2025 am 12:52 AM

The key to creating a custom page template is to understand the platform mechanism and follow the specifications. 1. First, clarify the platform type and template structure. For example, WordPress defines templates through PHP files with specific annotations, Hugo places the templates in the layouts directory, and React introduces layouts in a componentized manner. 2. Organize files according to naming and storing rules, such as putting WordPress templates on the theme root directory, Hugo uses baseof.html as the base template, and Jekyll references the template through the layout field in the \_layouts folder to avoid path or configuration errors. 3. Use template inheritance to improve reusability, define the basic template and cover some content in the specific page, reduce duplicate code and maintain

How to handle external API calls securely How to handle external API calls securely Jul 24, 2025 am 12:07 AM

To securely call external APIs, you need to start from three aspects: access control, data protection and response verification. ① Use APIKey, OAuthToken or JWT and store the key in environment variables or key management services, and rotate regularly; avoid the front-end exposing the key, select OAuth2.0 and adopt the appropriate authorization mode. ② Verify the structure and content of the data returned by the interface, confirm the Content-Type and field types, check the status code, filter the XSS content, and set a reasonable timeout time. ③ Use token bucket or leak bucket algorithm to achieve current limiting, record user API usage, and reduce duplicate requests in combination with cache to prevent triggering the other party from limiting the current or blocking the IP.

See all articles