wordpress添加媒体

tech2022-12-29  100

wordpress添加媒体

Inserting a media file into a post with WordPress is not very complicated thanks to the dedicated button present by default. However, if you develop a plugin using media files, this button won’t help your users insert the code needed by your functions.

由于默认情况下显示专用按钮,因此用WordPress将媒体文件插入帖子不是很复杂。 但是,如果您使用媒体文件开发插件,则此按钮将无法帮助您的用户插入功能所需的代码。

Fortunately, it is possible to add you own media button, so you can make it do whatever you want, properly.

幸运的是,可以添加您自己的媒体按钮,这样您就可以使其适当地执行任何操作。

In this tutorial, we will review how to add a media button in the right place, how to open the media window when the user clicks on it and, finally, how to get the selected items in order to insert them simultaneously into both visual and HTML editors.

在本教程中,我们将回顾如何在正确的位置添加媒体按钮,如何在用户单击时打开媒体窗口,以及最后如何获得所选项目以便将其同时插入到可视和可视项目中。 HTML编辑器。

添加媒体按钮 (Add a Media Button)

Adding our media button is the first and easiest part. As with customising many things in WordPress, we will use actions to put our button in the right place.

添加我们的媒体按钮是第一个也是最简单的部分。 与在WordPress中自定义许多内容一样,我们将使用操作将按钮放置在正确的位置。

Begin by creating a new function in the dedicated file of your plugin or theme (e.g. functions.php). For this tutorial, I will use a function named add_my_media_button(). Hook your function to the media_buttons action which is, as its name suggests it, the action called when WordPress is displaying the media buttons.

首先在插件或主题的专用文件中创建一个新函数(例如,functions.php)。 在本教程中,我将使用名为add_my_media_button()的函数。 将函数连接到media_buttons操作,顾名思义,该操作是WordPress显示媒体按钮时调用的操作。

add_action('media_buttons', 'add_my_media_button');

As you can imagine, we now need to modify our function to display our button, in the right way. We want our button to have the same style as the default one.

可以想象,我们现在需要修改功能以正确的方式显示按钮。 我们希望按钮的样式与默认样式相同。

Media buttons are not real buttons, they are links with the style of a button and WordPress give us a class for this style, named “button“.

媒体按钮不是真正的按钮,它们是按钮样式的链接,而WordPress为我们提供了这种样式的类,称为“ 按钮 ”。

function add_my_media_button() { echo '<a href="#" id="insert-my-media" class="button">Add my media</a>'; }

We give our button an ID. That way, we will be able to retrieve it later, in JavaScript.

我们给按钮一个ID。 这样,我们以后就可以使用JavaScript检索它。

Our custom media button is ready: it has the right style and almost the right place. In fact, by default, our new button is placed before the default one. If we want to place it after, it is possible by passing a third argument to the add_action() call in order to change our function’s priority.

我们的自定义媒体按钮已准备就绪:它具有正确的样式和几乎正确的位置。 实际上,默认情况下,我们的新按钮位于默认按钮之前。 如果我们想将其放置在后面,可以通过将第三个参数传递给add_action()调用来更改函数的优先级。

In fact, the function which displays the default media button has a priority of 10. Indicating a lower value for our function will place our button before the default one. If we want to place it after, we can indicate a greater value.

实际上,显示默认媒体按钮的功能的优先级为10。为我们的功能指示较低的值会将我们的按钮放在默认按钮之前。 如果我们希望将其放置在后面,则可以指定更大的值。

add_action('media_buttons', 'add_my_media_button', 15);

And that’s it! Now we have to make our button more useful.

就是这样! 现在我们必须使按钮更有用。

打开媒体窗口 (Open the Media Window)

To open the media window, we will use JavaScript with jQuery which is included in WordPress by default. First, we create a JS file. I chose to name it media_button.js but, of course, you are free to choose your own name.

要打开媒体窗口,默认情况下,我们将在WordPress中使用JavaScript和jQuery。 首先,我们创建一个JS文件。 我选择将其命名为media_button.js但是,当然,您可以自由选择自己的名称。

包括JavaScript文件 (Include the JavaScript File)

If you are familiar with WordPress, you should know that the CMS gives us a proper way to include the JS files we need. To do that, we create a function in which we use the WordPress function wp_enqueue_script().

如果您熟悉WordPress,则应该知道CMS为我们提供了一种包含所需JS文件的正确方法。 为此,我们创建一个使用WordPress函数wp_enqueue_script()函数。

function include_media_button_js_file() { wp_enqueue_script('media_button', 'path/to/media_button.js', array('jquery'), '1.0', true); }

As you can see, we indicate jQuery as a dependency. Thanks to the last argument, I chose to include the script in the footer but you can put it in the header if you prefer.

如您所见,我们将jQuery表示为依赖项。 由于有了最后一个参数,我选择将脚本包含在页脚中,但可以根据需要将其放在页眉中。

We created a function in order to ask WordPress to include our script only if it is necessary. For that, we will use another action: wp_enqueue_media, which is triggered when WordPress calls all the scripts needed by the media buttons.

我们创建了一个函数,以要求WordPress仅在必要时包括我们的脚本。 为此,我们将使用另一个操作: wp_enqueue_media ,当WordPress调用媒体按钮所需的所有脚本时触发。

add_action('wp_enqueue_media', 'include_media_button_js_file');

构造窗口 (Construct the Window)

To be able to use the jQuery function $(), we encapsulate the content of our media_button.js file in the jQuery() function. Then, we create a new function which will open the media window when the user clicks on our button.

为了能够使用jQuery函数$() ,我们将media_button.js文件的内容封装在jQuery()函数中。 然后,我们创建一个新功能,当用户单击我们的按钮时,它将打开媒体窗口。

jQuery(function($) { $(document).ready(function(){ $('#insert-my-media').click(open_media_window); }); function open_media_window() { } });

A media window is an instance of the wp.media object. Its constructor admits one parameter which is another object containing some attributes for the window. So the open_media_window_() function above may contain the following:

媒体窗口是wp.media对象的实例。 它的构造函数接受一个参数,该参数是另一个包含窗口某些属性的对象。 因此,上面的open_media_window_()函数可能包含以下内容:

function open_media_window() { var window = wp.media({ title: 'Insert a media', library: {type: 'image'}, multiple: false, button: {text: 'Insert'} }); }

The title attribute will be displayed as the title of the window. Be careful, the value of the button attribute is an object which admits a text attribute to set the label of the button on which the user will click to validate its choice.

title属性将显示为窗口的标题。 请注意, button属性的值是一个对象,该对象允许一个text属性设置按钮的标签,用户将在该标签上单击以验证其选择。

The library attribute will be used by WordPress to filter the media files displayed in the window. In this example, only the images can be selected. Moreover, the user won’t be able to chose more than one file thanks to the false value for the multiple attribute.

WordPress将使用library属性来过滤窗口中显示的媒体文件。 在此示例中,只能选择图像。 此外,由于multiple属性的false值,用户将无法选择多个文件。

None of these attributes are really required by WordPress. However, if you don’t indicate a title, your window will be untitled. By default, the multiple attribute is set to false and the displayed media files are not filtered.

WordPress实际上并不需要这些属性。 但是,如果您未指定标题,则您的窗口将无标题。 默认情况下, multiple属性设置为false并且不过滤显示的媒体文件。

使用媒体窗口 (Use the Media Window)

检索用户的选择 (Retrieve the User’s Selection)

The following code goes inside the open_media_window() function we created above.

以下代码位于我们上面创建的open_media_window()函数中。

For the moment, our window is constructed but it is not opened. To open the window, you can use the open() method but, before, you may want to retrieve the user’s selection.

目前,我们的窗口已构建,但尚未打开。 要打开窗口,可以使用open()方法,但是在此之前,您可能需要检索用户的选择。

To do that, we will use a special event created by WordPress for the media windows: select. Attach a function to this event require the use of the on() method.

为此,我们将使用WordPress创建的特殊事件作为媒体窗口: select 。 将函数附加到此事件需要使用on()方法。

window.on('select', function(){ var selection = window.state().get('selection'); });

The user’s selection is now stored in the variable selection. Depending on whether or not you allow multiple choice, the use of this variable is different.

现在,用户的选择存储在变量selection 。 根据是否允许多项选择,此变量的用法有所不同。

If the user can only chose one file, you can retrieve it with the first() method. Then you can convert the obtained object to JSON in order to get the information you want. Replace the above window.on event with:

如果用户只能选择一个文件,则可以使用first()方法进行检索。 然后,您可以将获取的对象转换为JSON,以获得所需的信息。 将上述window.on事件替换为:

window.on('select', function(){ var first = window.state().get('selection').first().toJSON(); });

This JSON object contains all you need about the chosen file. For instance, you can access the file’s ID with the id attribute while the file’s URL is accessible via the url attribute.

该JSON对象包含您需要的所有与所选文件有关的内容。 例如,您可以使用id属性访问文件的ID,而可以通过url属性访问文件的URL。

If you want to know what attributes can be used, you can for example list all of them in your browser’s console.

如果您想知道可以使用哪些属性,可以在浏览器的控制台中列出所有这些属性。

for (attr in first) console.log(attr);

If the user can select multiple files, you can convert the selection to an Array. Then you can retrieve each file’s data with the toJSON() method, exactly as in the first case. Replace the above window.on event with:

如果用户可以选择多个文件,则可以将选择内容转换为数组。 然后,您可以使用toJSON()方法检索每个文件的数据,与第一种情况完全相同。 将上述window.on事件替换为:

window.on('select', function(){ var files = window.state().get('selection').toArray(); var first = files[0].toJSON(); });

The files Array is sorted: the 0 entry contains the first file selected by the user, the 1 entry contains the second file, and so on.

files Array被排序: 0条目包含用户选择的第一个文件, 1条目包含第二个文件,依此类推。

在编辑器中插入文字 (Insert Text in the Editor)

Now that we retrieved the user’s choice, we would insert some text in the editor. To do that, we will use the WordPress function wp.media.editor.insert() which admits one parameter: the text to insert at the cursor’s current position.

现在我们检索了用户的选择,我们将在编辑器中插入一些文本。 为此,我们将使用WordPress函数wp.media.editor.insert() ,该函数wp.media.editor.insert()一个参数:要在光标当前位置插入的文本。

// Assume that we converted the first selected file to JSON wp.media.editor.insert('[myshortcode id="' + first.id + '"]');

The advantage of using this function is that WordPress will automatically insert our text in both visual and HTML editors.

使用此功能的优点是WordPress会自动在可视和HTML编辑器中插入我们的文本。

优化 (Optimization)

Our window is ready to be used. However, a problem persists: it will be reconstructed each time the user hits the button so we will change this behavior.

我们的窗口已准备就绪,可以使用。 但是,问题仍然存在:每次用户按下按钮时都会重新构造它,因此我们将更改此行为。

function open_media_window() { if (this.window === undefined) { this.window = wp.media({ title: 'Insert a media', library: {type: 'image'}, multiple: false, button: {text: 'Insert'} }); var self = this; // Needed to retrieve our variable in the anonymous function below this.window.on('select', function() { var first = self.window.state().get('selection').first().toJSON(); wp.media.editor.insert('[myshortcode id="' + first.id + '"]'); }); } this.window.open(); return false; }

First we check if the window has already been created and, if not, we create it. Then, we open our window and we finish the open_media_window() function with the instruction return false; in order to prevent the default behavior of the link.

首先,我们检查窗口是否已经创建,如果没有,则创建它。 然后,我们打开窗口,并使用return false;指令完成open_media_window()函数return false; 为了防止链接的默认行为。

Note that there exists more than one way to prevent the problem indicated above. However, the scheme is always the same and you can adapt your favorite method easily.

请注意,存在多种防止上述问题的方法。 但是,方案始终相同,您可以轻松地调整自己喜欢的方法。

结论 (In Conclusion)

You now know how to add a media button and how to use it to insert some text related to the user’s choice in the editor. If you listed the attributes of the data variable we created above, you may have noticed that WordPress give us all the information about the chosen media file, meaning you can do whatever you want with it.

现在,您知道了如何添加媒体按钮,以及如何使用它在编辑器中插入一些与用户选择有关的文本。 如果您列出了上面创建的data变量的属性,则可能已经注意到WordPress为我们提供了有关所选媒体文件的所有信息,这意味着您可以使用它进行任何操作。

翻译自: https://www.sitepoint.com/adding-a-media-button-to-the-content-editor/

wordpress添加媒体

最新回复(0)