WordPress wp_media modalに画像選択を事前入力します


32

私はAdvanced Custom Fieldsプラグインの開発者であり、私が直面している問題で私を助けてくれることを望んでいます。

画像を編集できるボタンがあります。このボタンは、wp_media()関数を介してWP 3.5メディアモーダルを起動します。

問題は、サイドバーパネルに詳細が読み込まれるように画像を事前に選択することです。

現在、私は 'open'コールバックにフックして、この選択に値を設定するコードを実行していますが、不格好で効率的です。これは次のようになります。

// _media is an object I am using

_media.frame = wp.media({
    title       :   'title',
    multiple    :   false,
    button      :   { text : 'button' }
});


// open
_media.frame.on('open',function() {


    // add class
    _media.frame.$el.closest('.media-modal').addClass('acf-media-modal acf-expanded');


    // set selection
    var selection   =   _media.frame.state().get('selection'),
        attachment  =   wp.media.attachment( id );


    attachment.fetch();
    selection.add( attachment );

});


// Finally, open the modal
_media.frame.open();

ユーザーが別のモーダルウィンドウを開き、アップロードタブを選択し、作成した編集ボタンを使用するまで、これは正常に機能しています。これで、コードは「ブラウズ」モードのモーダルに依存しているため、コードは完全に失敗します。

フレームをブラウズモードに切り替えるコードを見つけました。次のようになります。

_media.frame.content.mode('browse');

これは時々機能しますが、次のコードは失敗します。添付ファイルを選択に追加する前にレンダリングするのに時間がかかるように...

確かにもっと良い方法があります。

ご協力いただきありがとうございます。エリオット


この質問は複雑であるため、WPSEユーザーがgithub、meta.wordpress.stackexchange.com / questions / 2572
Wyck

回答:


3

スクリプトは次のとおりです。

私はloadImages次のスクリプトで関数を使用して、既存の添付画像をAJAX経由でロードし、画像のIDを持つ関数を渡すだけで、事前に入力されたモーダルを開きます。

var frame,
selection = loadImages(images);

$('#stag_images_upload').on('click', function(e) {
    e.preventDefault();

var options = {
    title: '<?php _e("Create Featured Gallery", "stag"); ?>',
    state: 'gallery-edit',
    frame: 'post',
    selection: selection
};

frame = wp.media(options).open();

frame.menu.get('view').unset('cancel');
frame.menu.get('view').unset('separateCancel');
frame.menu.get('view').get('gallery-edit').el.innerHTML = '<?php _e("Edit Featured Gallery", "stag"); ?>';
frame.content.get('view').sidebar.unset('gallery'); // Hide Gallery Settings in sidebar

// when editing a gallery
overrideGalleryInsert();
frame.on( 'toolbar:render:gallery-edit', function() {
    overrideGalleryInsert();
});

frame.on( 'content:render:browse', function( browser ) {
    if ( !browser ) return;
    // Hide Gallery Settings in sidebar
    browser.sidebar.on('ready', function(){
        browser.sidebar.unset('gallery');
    });

    // Hide filter/search as they don't work
    browser.toolbar.on('ready', function(){
        if(browser.toolbar.controller._state == 'gallery-library'){
            browser.toolbar.$el.hide();
        }
    });
});

// All images removed
frame.state().get('library').on( 'remove', function() {
    var models = frame.state().get('library');
    if(models.length == 0){
        selection = false;
        $.post(ajaxurl, { ids: '', action: 'stag_save_images', post_id: stag_ajax.post_id, nonce: stag_ajax.nonce });
    }
});

function overrideGalleryInsert(){
    frame.toolbar.get('view').set({
        insert: {
            style: 'primary',
            text: '<?php _e("Save Featured Gallery", "stag"); ?>',
            click: function(){
                var models = frame.state().get('library'),
                    ids = '';

                models.each( function( attachment ) {
                    ids += attachment.id + ','
                });

                this.el.innerHTML = '<?php _e("Saving...", "stag"); ?>';

                $.ajax({
                    type: 'POST',
                    url: ajaxurl,
                    data: { 
                        ids: ids, 
                        action: 'stag_save_images', 
                        post_id: stag_ajax.post_id, 
                        nonce: stag_ajax.nonce 
                    },
                    success: function(){
                        selection = loadImages(ids);
                        $('#_stag_image_ids').val( ids );
                        frame.close();
                    },
                    dataType: 'html'
                }).done( function( data ) {
                    $('.stag-gallery-thumbs').html( data );
                    console.log(data);
                });
            }
        }
    });
}

function loadImages(images){
    if (images){
        var shortcode = new wp.shortcode({
            tag:      'gallery',
            attrs:    { ids: images },
            type:     'single'
        });

        var attachments = wp.media.gallery.attachments( shortcode );

        var selection = new wp.media.model.Selection( attachments.models, {
            props:    attachments.props.toJSON(),
            multiple: true
        });

        selection.gallery = attachments.gallery;

        selection.more().done( function() {
            // Break ties with the query.
            selection.props.set({ query: false });
            selection.unmirror();
            selection.props.unset('orderby');
        });

        return selection;
    }
    return false;
}

});

そして、AJAXリクエストを処理するphp関数は次のとおりです。

function stag_save_images(){
    if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
        return;
    }

    if ( !isset($_POST['ids']) || !isset($_POST['nonce']) || !wp_verify_nonce( $_POST['nonce'], 'stag-ajax' ) ){
        return;
    }

    if ( !current_user_can( 'edit_posts' ) ) return;

    $ids = strip_tags(rtrim($_POST['ids'], ','));
    update_post_meta($_POST['post_id'], '_stag_image_ids', $ids);

    $thumbs = explode(',', $ids);
    $thumbs_output = '';
    foreach( $thumbs as $thumb ) {
        $thumbs_output .= '<li>' . wp_get_attachment_image( $thumb, array(75,75) ) . '</li>';
    }

    echo $thumbs_output;

    die();
}
add_action( 'wp_ajax_stag_save_images', 'stag_save_images' );

function stag_metabox_scripts(){
    global $post;
    if( isset($post) ) {
        wp_localize_script( 'jquery', 'stag_ajax', array(
            'post_id' => $post->ID,
            'nonce' => wp_create_nonce( 'stag-ajax' )
        ) );
    }
}

add_action( 'admin_enqueue_scripts', 'stag_metabox_scripts' );

WordPressフレームワークからスニペットをコピーしたばかりです。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.