Путь к файлу загрузки, не указанный в поле, с помощью загрузчика wp media


Я использую пользовательский media upload в своем плагине. В моих предыдущих версиях (before 4.0) WordPress он работал отлично. Когда я загружаю аудио или графический файл, его загрузка успешно выполняется

enter image description here

И когда я нажимаю на "Insert Into Post", путь к загруженному файлу отображается в текстовом поле.

enter image description here

Но когда я обновляю свой WordPress into 4.4.2 и загружаю любой файл, его загрузка успешно выполняется

enter image description here

И когда я нажимаю "Вставить в сообщение", путь к файлу загруженный файл не отображается в моем текстовом поле.

enter image description here

В обоих 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&amp;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, но она дает мне неопределенное значение. Поэтому, пожалуйста, помогите мне решить эту проблему

Author: deemi-D-nadeem, 2016-04-11

3 answers

Изменение, внесенное новым WordPress в их загрузку мультимедиа, - это пустое поле URL ссылки.

enter image description here

Но если вы нажмете кнопку 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
Author: Omer, 2016-04-21 14:23:50

Почему вы не используете 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
Author: dingo_d, 2016-04-15 12:14:42

Это новая версия загрузчика 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's 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');
    }
}
 1
Author: Jordane CURE, 2016-04-20 13:12:38