Загрузка Путь к файлу, который не показан в поле, используя загрузчик wp media
Я использую пользовательский media upload
в своем плагине. В моих предыдущих версиях (before 4.0) WordPress
он работал отлично. Когда я загружаю файл аудио или изображения, его загрузка успешно
![введите описание изображения здесь]()
и когда я нажимаю на "Insert Into Post"
путь к загруженному файлу, указанному в текстовом поле.
![введите описание изображения здесь]()
Но когда я обновляю свой WordPress into 4.4.2
и загружаю любой файл, его загрузка успешно
![введите описание изображения здесь]()
и когда я нажимаю "Вставить в сообщение" путь к файлу загруженного файла, не отображаемый в текстовом поле.
![введите описание изображения здесь]()
В обоих WordPress код на 100% тот же.
Вот мой код HTML:
<input type="text" size="50" name="mp3" id="mp3" class="upload-url" />
<input id="st_upload_button" class="st_upload_button" type="button" name="upload_button" value="Upload">
И вот мой код functions.php:
function pro_scripts_method() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script( 'custom-js', plugin_dir_url( __FILE__ )."js/custom.js");
wp_enqueue_script( 'custom-js' );
}
add_action('admin_enqueue_scripts', 'pro_scripts_method');
И вот мой код JS:
jQuery('.st_upload_button').click(function() {
targetfield = jQuery(this).prev('.upload-url');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
fileurl = jQuery(html).attr('href');
//alert(fileurl);
jQuery(targetfield).val(fileurl);
tb_remove();
}
Я предупреждаю переменную fileurl
, но она дает мне значение undefined. Поэтому, пожалуйста, помогите мне решить эту проблему.
Ответы
Ответ 1
Изменение, которое новый WordPress сделал для своей загрузки мультимедиа, - это пустое поле Ссылка URL.
![введите описание изображения здесь]()
Но если вы нажмете кнопку file url
ниже этого поля, а затем нажмите Insert Into Post
, ваш код хорошо работает:)
Итак, нам нужен простой способ автоматически поместить значение file url
в URL-адрес ссылки. Я не знаю об этом, есть ли параметр для этого в wordpress или нет, но есть простой код, который я написал в jQuery для его достижения, и он отлично работает для меня.
То, что я действительно делаю, это:
Когда пользователь нажал кнопку Insert Into Post
. Мой jQuery проверяет родительский элемент этой кнопки Insert Into Post
и находит значение file url
и вставляет его в поле Ссылка URL. Это! Просто так?
jQuery('.savesend input[type=submit]').click(function(){
var url = jQuery(this).parents('.describe').find('.urlfile').data('link-url');
var field = jQuery(this).parents('.describe').find('.urlfield');
field.val(url);
});
Итак, попробуйте и дайте мне знать:)
Ответ 2
Почему вы не используете wp.media
?
Попробуйте следующее:
jQuery(document).ready(function($) {
"use strict";
$('.st_upload_button').on('click', function(e){
e.preventDefault();
var $input_field = $(this).prev();
var custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Add Audio',
button: {
text: 'Add Audio'
},
multiple: false
});
custom_uploader.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$input_field.val(attachment.url);
});
custom_uploader.open();
});
});
Это откроет экран мультимедиа при нажатии кнопки и поместит URL в поле ввода.
Ответ 3
Это новая версия загрузчика wordpress с Wordpress 3.5. Возможно, способ, которым вы это сделали, недоступен в Wordpress 4.0
Здесь вы можете найти основной учебник:
http://www.webmaster-source.com/
jQuery(document).ready(function($){
var custom_uploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#upload_image').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
<label for="upload_image">
<input id="upload_image" type="text" size="36" name="ad_image" value="http://" />
<input id="upload_image_button" class="button" type="button" value="Upload Image" />
<br />Enter a URL or upload an image
</label>
//This part Should be in function.php (or similar)
add_action('admin_enqueue_scripts', 'my_admin_scripts');
function my_admin_scripts() {
if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') {
wp_enqueue_media();
wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery'));
wp_enqueue_script('my-admin-js');
}
}