用图像选择预填充WordPress wp_media模态


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

Answers:


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框架中复制了该代码段,希望它有意义。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.