programing

Metabox에서 WordPress 갤러리 업로더/실렉터 호출

css3 2023. 3. 1. 11:25

Metabox에서 WordPress 갤러리 업로더/실렉터 호출

투고/페이지에서 [미디어 추가]버튼을 클릭하면 [미디어 추가]옵션이 표시됩니다.미디어를 선택한 후 Insert Into Post를 클릭하면 이미지가 삽입됩니다.그러나 왼쪽 사이드바에 다른 옵션이 있습니다.[ Create Gallery ]을 클릭합니다.이미지 선택 프로세스는 동일하지만 Create New Gallery를 클릭하면 이미지 순서를 편집할 수 있는 새 프레임으로 이동합니다.

이 두 번째 창문이 내가 찾고 있는 거야저는 메타박스에서 프레임을 호출하고 있으며, 1개 또는 여러 개의 이미지를 캡처하여 ID를 문자열로 저장하거나 미리보기 상자에 라이브로 미리보기 이미지를 삽입할 수 있습니다.갤러리 프레임을 호출하는 방법을 찾을 수 없습니다.

현재 코드는 다음과 같습니다.

jQuery('#fg_select').on('click', function(event){

    event.preventDefault();

    // If the media frame already exists, reopen it.
    if ( file_frame ) {
        file_frame.open();
        return;
    }

    // Create the media frame.
    file_frame = wp.media.frame = wp.media({
        title: "Select Images For Gallery",
        button: {text: "Select",},
        library : { type : 'image'},
        multiple: true // Set to true to allow multiple files to be selected
    });

    file_frame.on('open', function() {
        var selection = file_frame.state().get('selection');
        ids = jQuery('#fg_metadata').val().split(',');
        ids.forEach(function(id) {
            attachment = wp.media.attachment(id);
            attachment.fetch();
            selection.add( attachment ? [ attachment ] : [] );
        });
    });

    file_frame.on('ready', function() {
        // Here we can add a custom class to our media modal.
        // .media-modal doesn't exists before the frame is
        // completly initialised.
        $( '.media-modal' ).addClass( 'no-sidebar' );
    });

    // When an image is selected, run a callback.
    file_frame.on('select', function() {
        var imageIDArray = [];
        var imageHTML = '';
        var metadataString = '';
        images = file_frame.state().get('selection');
        images.each(function(image) {
            imageIDArray.push(image.attributes.id);
            imageHTML += '<li><button></button><img id="'+image.attributes.id+'" src="'+image.attributes.url+'"></li>';
        });
        metadataString = imageIDArray.join(",");
        if(metadataString){
            jQuery("#fg_metadata").val(metadataString);
            jQuery("#featuredgallerydiv ul").html(imageHTML);
            jQuery('#fg_select').text('Edit Selection');
            jQuery('#fg_removeall').addClass('visible');
        }
    });

    // Finally, open the modal
    file_frame.open();

});

좋은 생각 있어요?

편집:

사이드바 없이 갤러리에 직접 전화하는 수준까지 왔습니다.다만, 온('select') 콜은 무시됩니다.갤러리에서는 이미지를 선택할 때 다른 콜을 보내는 것 같습니다.

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

// Uploading files
var file_frame;

jQuery('#fg_select').on('click', function(event){

    event.preventDefault();

    // If the media frame already exists, reopen it.
    if ( file_frame ) {
        file_frame.open();
        return;
    }

    // Create the media frame.
    file_frame = wp.media.frame = wp.media({
        frame: "post",
        state: "featured-gallery",
        library : { type : 'image'},
        button: {text: "Edit Image Order"},
        multiple: true
    });

    file_frame.states.add([
        new wp.media.controller.Library({
            id:         'featured-gallery',
            title:      'Select Images for Gallery',
            priority:   20,
            toolbar:    'main-gallery',
            filterable: 'uploaded',
            library:    wp.media.query( file_frame.options.library ),
            multiple:   file_frame.options.multiple ? 'reset' : false,
            editable:   true,
            allowLocalEdits: true,
            displaySettings: true,
            displayUserSettings: true
        }),
    ]);

    file_frame.on('open', function() {
        var selection = file_frame.state().get('selection');
        ids = jQuery('#fg_metadata').val().split(',');
        if (!empty(ids)) {
            ids.forEach(function(id) {
                attachment = wp.media.attachment(id);
                attachment.fetch();
                selection.add( attachment ? [ attachment ] : [] );
            });
        }
    });

    file_frame.on('ready', function() {
        // Here we can add a custom class to our media modal.
        // .media-modal doesn't exists before the frame is
        // completly initialised.
        $( '.media-modal' ).addClass( 'no-sidebar' );
    });

    file_frame.on('change', function() {
        // Here we can add a custom class to our media modal.
        // .media-modal doesn't exists before the frame is
        // completly initialised.
        setTimeout(function(){
            $('.media-menu a:first-child').text('← Edit Selection').addClass('button').addClass('button-large').addClass('button-primary');
        },0);
    });

    // When an image is selected, run a callback.
    file_frame.on('set', function() {
        alert('test');
    });

    // Finally, open the modal
    file_frame.open();

});

편집 2:

좋아, 내가 모든 걸 정확하게 발사했어.하지만 출력된 갤러리 코드를 해독할 수 없습니다.

        // When an image is selected, run a callback.
    file_frame.on('update', function() {
        var imageIDArray = [];
        var imageHTML = '';
        var metadataString = '';
        images = file_frame.state().get('selection');
        images.each(function(image) {
            imageIDArray.push(image.attributes.id);
            imageHTML += '<li><button></button><img id="'+image.attributes.id+'" src="'+image.attributes.url+'"></li>';
        });
        metadataString = imageIDArray.join(",");
        if (metadataString) {
            jQuery("#fg_metadata").val(metadataString);
            jQuery("#featuredgallerydiv ul").html(imageHTML);
            jQuery('#fg_select').text('Edit Selection');
            jQuery('#fg_removeall').addClass('visible');
        }
    });

$image에 대한 정보는 없습니다.어레이 또는 $imageHTML. $image는 [객체 객체]입니다.

EDIT 3: 코멘트에 기재된 바와 같이 Edit 2의 코드에 관한 주요 문제는 갤러리를 이용할 때 '선택'이 아닌 '도서관'으로 전화해야 한다는 것입니다.

    // Uploading files
var file_frame;

jQuery('#fg_select').on('click', function(event){

    event.preventDefault();

    // If the media frame already exists, reopen it.
    if ( file_frame ) {
        file_frame.open();
        return;
    }

    // Create the media frame.
    file_frame = wp.media.frame = wp.media({
        frame: "post",
        state: "gallery",
        library : { type : 'image'},
        button: {text: "Edit Image Order"},
        multiple: true
    });

    file_frame.on('open', function() {
        var selection = file_frame.state().get('selection');
        var ids = jQuery('#fg_metadata').val();
        if (ids) {
            idsArray = ids.split(',');
            idsArray.forEach(function(id) {
                attachment = wp.media.attachment(id);
                attachment.fetch();
                selection.add( attachment ? [ attachment ] : [] );
            });
        }
    });

    // When an image is selected, run a callback.
    file_frame.on('update', function() {
        var imageIDArray = [];
        var imageHTML = '';
        var metadataString = '';
        images = file_frame.state().get('library');
        images.each(function(attachment) {
            imageIDArray.push(attachment.attributes.id);
            imageHTML += '<li><button></button><img id="'+attachment.attributes.id+'" src="'+attachment.attributes.url+'"></li>';
        });
        metadataString = imageIDArray.join(",");
        if (metadataString) {
            jQuery("#fg_metadata").val(metadataString);
            jQuery("#featuredgallerydiv ul").html(imageHTML);
            jQuery('#fg_select').text('Edit Selection');
            jQuery('#fg_removeall').addClass('visible');
        }
    });

    // Finally, open the modal
    file_frame.open();

});

여기서 가장 어려운 점은 선택해서 갤러리 편집을 할 수 없다는 것입니다.거기서 열 수 있는데 이미지가 선택되지 않았습니다.알아보는 중이에요새로운 뷰를 생성하여 사전선택을 보내는 대신 다시 여는 것도 검토하고 있습니다.선택창에서 주문창으로 이동하여 X를 클릭하여 닫으면 주문창으로 다시 열 수 있습니다.그러니 방법이 있을 거야

편집 4

아래 답변의 코드에 따라 사전 선택 코드를 다음과 같이 변경했습니다.

    file_frame.on('open', function() {
        var library = file_frame.state().get('library');
        var ids = jQuery('#fg_perm_metadata').val();
        if (ids) {
            idsArray = ids.split(',');
            idsArray.forEach(function(id) {
                attachment = wp.media.attachment(id);
                attachment.fetch();
                library.add( attachment ? [ attachment ] : [] );
            });
        }
    });

그러면 갤러리 편집 상태로 직접 다시 열어서 이미지를 미리 선택할 수 있습니다.그러나 이 상태로 직접 열었을 때 Cancel Gallery(갤러리 취소)(이미지 선택 상태로 돌아가기)를 클릭할 수 없습니다.이 버튼/링크를 클릭하면 프레임이 닫힙니다.도서관과 도서관을 모두 미리 채워보려고 했는데 그것도 안 돼요.다음은 media-views.js에서 가져온 것으로, 이 버튼을 제어하는 것 같습니다.상태를 특정 상태로 변경하는 대신 이전 상태로 변경합니다.갤러리 편집을 직접 오픈하기 때문에 과거 상태는 없습니다.갤러리를 열고 열어서 갤러리 편집으로 변경할 수 있는지 궁금합니다.사용자가 볼 수 없도록 즉시 실행하되, 과거 상태를 시스템에 반영하도록 합니다.

    galleryMenu: function( view ) {
    var lastState = this.lastState(),
        previous = lastState && lastState.id,
        frame = this;

편집 5:

마침내 모든 걸 알아냈어나는 위 사항을 전혀 실행하지 못했는데, 왜 그랬는지 모르겠다.그래서 더 좋은 방법이 있을지도 몰라 그 코드를 포함해서 말이야만약 그렇다면, 알고 싶어요.

    file_frame.on('open', function() {
        var selection = file_frame.state().get('selection');
        var library = file_frame.state('gallery-edit').get('library');
        var ids = jQuery('#fg_perm_metadata').val();
        if (ids) {
            idsArray = ids.split(',');
            idsArray.forEach(function(id) {
                attachment = wp.media.attachment(id);
                attachment.fetch();
                selection.add( attachment ? [ attachment ] : [] );
            });
            file_frame.setState('gallery-edit');
            idsArray.forEach(function(id) {
                attachment = wp.media.attachment(id);
                attachment.fetch();
                library.add( attachment ? [ attachment ] : [] );
            });
        }
    });

최종 편집

코드가 완전히 기능하고 있습니다.도와주셔서 감사합니다!실제 가동 상황을 보고 싶다면 http://wordpress.org/plugins/featured-galleries/를 참조하십시오.

저는 WP에 비교적 익숙하지 않습니다.사실, 나는 나의 첫 번째 WP 테마를 만들고 있는데 당신과 같은 질문에서 벗어나지 못하고 있습니다.당신의 코드 덕분에 갤러리 페이지로 이동할 수 있습니다.그리고 다행히도, 저는 이미지를 저장했습니다.제 코드는 다음과 같습니다.

// when click Insert Gallery, run callback
wp_media_frame.on('update', function(){
    var library = wp_media_frame.state().get('library');
    var images  = [];
    var image_ids = [];
    thumb_wraper.html('');

    library.map( function( image ) {
        image = image.toJSON();
        images.push(image.url);
        image_ids.push(image.id);
        thumb_wraper.append('<img src="' + image.url + '" alt="" />');
    });
});

내가 발견한 것은 당신이 '선택'을 받는 것이 아니라 '도서관'을 받아야 한다는 것입니다.

편집: 갤러리 편집으로 돌아가는 방법을 알아냈습니다.자세한 코드는 다음과 같습니다.

    $( '#btn_upload' ).on( 'click', function( event ) {
    event.preventDefault();

    var images = $( '#image_ids' ).val();
    var gallery_state = images ? 'gallery-edit' : 'gallery-library';

    // create new media frame
    // You have to create new frame every time to control the Library state as well as selected images
    var wp_media_frame = wp.media.frames.wp_media_frame = wp.media( {
        title: 'My Gallery', // it has no effect but I really want to change the title
        frame: "post",
        toolbar: 'main-gallery',
        state: gallery_state,
        library: {
            type: 'image'
        },
        multiple: true
    } );

    // when open media frame, add the selected image to Gallery
    wp_media_frame.on( 'open', function() {
        var images = $( '#image_ids' ).val();
        if ( !images )
            return;

        var image_ids = images.split( ',' );
        var library = wp_media_frame.state().get( 'library' );
        image_ids.forEach( function( id ) {
            attachment = wp.media.attachment( id );
            attachment.fetch();
            library.add( attachment ? [ attachment ] : [] );
        } );
    } );

    // when click Insert Gallery, run callback
    wp_media_frame.on( 'update', function() {

        var thumb_wrapper = $( '#thumb-wrapper' );
        thumb_wraper.html( '' );
        var image_urls = [];
        var image_ids = [];

        var library = wp_media_frame.state().get( 'library' );

        library.map( function( image ) {
            image = image.toJSON();
            image_urls.push( image.url );
            image_ids.push( image.id );
            thumb_wrapper.append( '<img src="' + image.url + '" alt="" />' );
        } );
    } );
} );

기존 프레임을 다시 열면 항상 초기 상태가 유지되고, 당신의 경우 '갤러리'라고 생각됩니다.매번 새로운 프레임을 만들고 '갤러리 편집'을 열 이미지가 있는지 확인해야 합니다. 또한, 저는 사용자가 제 갤러리에 집중하기를 원하기 때문에 '갤러리'보다 '갤러리 라이브러리'를 선호합니다.

언급URL : https://stackoverflow.com/questions/21858112/calling-wordpress-gallery-uploader-selector-from-metabox