Home >CMS Tutorial >WordPress >Using the WordPress Theme Customizer Media Controls

Using the WordPress Theme Customizer Media Controls

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-15 10:29:14330browse

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.

<code class="language-php">function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');</code>
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".

<code class="language-php">$wp_customize->add_section('sound', array(
    'title' => 'Sound',
    'description' => 'Add a sound to your website',
    'capability' => 'edit_theme_options'
));</code>

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.

<code class="language-php">$wp_customize->add_setting('music', array(
    'type' => 'theme_mod',
    'capability' => 'edit_theme_options',
    'sanitize_callback' => 'absint'
));</code>

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.

<code class="language-php">$wp_customize->add_control(new WP_Customize_Media_Control($wp_customize, 'music', array(
    'section' => 'sound',
    'label' => 'Music',
    'mime_type' => 'audio'
)));</code>

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.

<code class="language-php">function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');</code>

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.

<code class="language-php">$wp_customize->add_section('sound', array(
    'title' => 'Sound',
    'description' => 'Add a sound to your website',
    'capability' => 'edit_theme_options'
));</code>

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.

<code class="language-php">function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');</code>

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.

<code class="language-php">$wp_customize->add_section('sound', array(
    'title' => 'Sound',
    'description' => 'Add a sound to your website',
    'capability' => 'edit_theme_options'
));</code>

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.

<code class="language-php">$wp_customize->add_setting('music', array(
    'type' => 'theme_mod',
    'capability' => 'edit_theme_options',
    'sanitize_callback' => 'absint'
));</code>

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.

<code class="language-php">function add_my_media_controls($wp_customize) {
}
add_action('customize_register', 'add_my_media_controls');</code>

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:
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