Program Tip

테마 옵션에 대한 WordPress 3.5 사용자 정의 미디어 업로드

programtip 2020. 11. 15. 11:39
반응형

테마 옵션에 대한 WordPress 3.5 사용자 정의 미디어 업로드


워드 프레스 3.5가 최근에 출시되었는데, 저는 두꺼운 상자를 통해 워드 프레스 미디어 업로드 시스템을 사용했고 워드 window.send_to_editor프레스 테마의 일부 옵션 (배경, 로고 등)을 사용했습니다.

하지만 아시다시피 WordPress에 새로운 미디어 관리자가 통합 되었기 때문에이 새로운 기능을 사용하여 이미지 / 파일을 사용자 정의 필드로 업로드하고 싶었습니다. 그래서 원하는 결과를 얻을 수있는 방법을 찾기 위해 아침을 보냈습니다.

이 솔루션을 사용하면 일부 사용자에게 유용 할 수 있습니다. 코드에 대한 피드백이나 염두에두고있는 개선 사항을 알려 주셔서 감사합니다!

HTML 샘플 :

<a href="#" class="custom_media_upload">Upload</a>
<img class="custom_media_image" src="" />
<input class="custom_media_url" type="text" name="attachment_url" value="">
<input class="custom_media_id" type="text" name="attachment_id" value="">

jQuery 코드 :

$('.custom_media_upload').click(function() {

    var send_attachment_bkp = wp.media.editor.send.attachment;

    wp.media.editor.send.attachment = function(props, attachment) {

        $('.custom_media_image').attr('src', attachment.url);
        $('.custom_media_url').val(attachment.url);
        $('.custom_media_id').val(attachment.id);

        wp.media.editor.send.attachment = send_attachment_bkp;
    }

    wp.media.editor.open();

    return false;
});

당신이보고 싶은 경우 모든 설정이 포함 attachment당신이 할 수있는 변수 console.log(attachment)alert(attachment).


wp_enqueue_media게시물 편집 페이지에 있지 않다면 (3.5의 새로운 기능) 을 사용하는 것을 잊지 마십시오

이전 미디어 업로드 상자를 사용하려면 다음을 수행하십시오.

if(function_exists( 'wp_enqueue_media' )){
    wp_enqueue_media();
}else{
    wp_enqueue_style('thickbox');
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
}

의도하지 않은 방식으로 진행합니다. 자바 스크립트 코드는 다음과 같이 보일 것입니다.

$('.custom_media_upload').click(function(e) {
    e.preventDefault();

    var custom_uploader = wp.media({
        title: 'Custom Title',
        button: {
            text: 'Custom Button Text'
        },
        multiple: false  // Set this to true to allow multiple files to be selected
    })
    .on('select', function() {
        var attachment = custom_uploader.state().get('selection').first().toJSON();
        $('.custom_media_image').attr('src', attachment.url);
        $('.custom_media_url').val(attachment.url);
        $('.custom_media_id').val(attachment.id);
    })
    .open();
});

한 번에 여러 필드에 사용할 수 있도록이 코드를 조금 더 수정했습니다.

HTML :

<!-- Image Thumbnail -->
<img class="custom_media_image" src="" style="max-width:100px; float:left; margin: 0px     10px 0px 0px; display:inline-block;" />

<!-- Upload button and text field -->
<input class="custom_media_url" id="" type="text" name="" value="" style="margin-bottom:10px; clear:right;">
<a href="#" class="button custom_media_upload">Upload</a>

jQuery :

jQuery(document).ready(function($){

$('.custom_media_upload').click(function() {

        var send_attachment_bkp = wp.media.editor.send.attachment;
        var button = $(this);

        wp.media.editor.send.attachment = function(props, attachment) {

            $(button).prev().prev().attr('src', attachment.url);
            $(button).prev().val(attachment.url);

            wp.media.editor.send.attachment = send_attachment_bkp;
        }

        wp.media.editor.open(button);

        return false;       
    });

});

편집기가 닫히면 사용자 지정 함수를 트리거 할 수있는 항목이 없습니다. 나는 이것을 사용한다 :

wp.media.editor.open();
$('.media-modal-close, .media-modal-backdrop').one('click', function(){
    //do some stuff
});

이상 :

var id = wp.media.editor.id();
var editor = wp.media.editor.get( id );
if('undefined' != typeof( editor )) editor = wp.media.editor.add( id );

if ( editor ) {
    editor.on('close', function(){
        //do some stuff
    });
}

나는 이것을 가지고 놀 기회가 많지 않았지만 갤러리 요소를 활용하려는 사람들에게는이 코드가 당신의 길을 안내합니다.

시작점 일뿐입니다. 쉼표로 구분 된 이미지 ID 목록 만 제공하지만 창의력을 발휘하기에 충분합니다.

<input id="custom_media_id" type="text" name="attachment_id" value="">
<a href="#" class="button custom_media_upload" title="Add Media">Add Media</a>

<script type="text/javascript">
  jQuery('.custom_media_upload').click(function() {
    var clone = wp.media.gallery.shortcode;
    wp.media.gallery.shortcode = function(attachments) {
    images = attachments.pluck('id');
    jQuery('#custom_media_id').val(images);
    wp.media.gallery.shortcode = clone;
    var shortcode= new Object();
    shortcode.string = function() {return ''};
    return shortcode;
  }
jQuery(this).blur(); // For Opera. See: http://core.trac.wordpress.org/ticket/22445
wp.media.editor.open();
return false;       
});
</script>

이렇게하면 편집기에서 설정된 순서대로 쉼표로 구분 된 이미지 ID 목록으로 입력 필드가 채워집니다 (새로운 끌어서 놓기 기능 사용).

The function expects the shortcode to be sent back for placement in the main editor, but we don't want to do this, so we create a new object that returns a blank string for insertion.

Also note, this doesn't handle inserting a single image as described above - it'll just put it into the post editor. So try combining the two listeners, or remove the appropriate tabs.

EDIT

Having spent some time looking at the core, I think this whole process can actually be done easier using the technique laid out here, but as you'll read I haven't figured out yet how to pre-select the images when you reopen the media manager.

참고URL : https://stackoverflow.com/questions/13847714/wordpress-3-5-custom-media-upload-for-your-theme-options

반응형