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'sfunctions.php
file or to a new plug-in. -
WP_Customize_Media_Control
can be extended to add more features, such as theWP_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');
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.
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!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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











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

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.

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

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

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

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.
