如何在元字段中创建画廊时获取wp库的短代码

时间:2017-02-20 12:14:44

标签: jquery wordpress image-uploading shortcode media-library

我在元字段上创建了一个图库媒体加载器。它的工作完美。

enter image description here

当我点击<div id="panel"> <div id="title"> Panel title </div> <div id="content"> <div id="chat"> <div id="chatmessages"> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> <div>Hello World</div> </div> <div id="chatbox"> <input value="this will be a chat box" /> </div> </div> </div> </div>时,图库媒体加载器已打开,我选择图像然后点击Browse但我没有在输入元字段中获取图库的短代码

以下是我从互联网上获取的代码:

Insert Gallery

这是我的HTML代码:

var meta_image_frame_gallery;
    $( '#additional_image_1' ).click(function( event ) {
        event.preventDefault();

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

        if ( meta_image_frame_gallery ) {
            meta_image_frame_gallery.open();
            return;
        }

        // create new media frame
        // You have to create new frame every time to control the Library state as well as selected images
        meta_image_frame_gallery = 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-library',
            library: {
                type: 'image'
            },
            multiple: true
        } );

    } );

我在jquery中非常弱,所以请指导我这个问题

2 个答案:

答案 0 :(得分:2)

你需要

  • 为wp.media框架添加'close'事件
  • 从close事件中的wp.media获取短代码并将其传递给输入
  • 在wordpress上添加save_action挂钩,以便在保存/发布帖子时保存此值
  • 另外,您可能需要从输入中获取当前图库项目并将其传递给wp.media框架,以便使用可以查看以前选择的图像。

您可以使用以下工作代码并在WordPress安装上进行测试。

//add action for the custom gallery
add_action("add_meta_boxes", "add_custom_meta_box_gallery");
function add_custom_meta_box_gallery()
{
    add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_gallery_markup", "post");
}

function custom_meta_box_gallery_markup($object)
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");
    ?>
    <div>
        <label for="meta-box-text">Gallery</label>
        <!-- avoid double quote for with value as shortcode string also has doulbe qoutes. so instead of value="..." use value='....' -->
        <input value='<?php echo get_post_meta($object->ID, "meta-box-gallery", true); ?>' id="itv_additional_image_1" class="input-text" name="meta-box-gallery" placeholder="" type="text">
        <input id="additional_image_1" name="additional_image_1" value="Browse" type="button">
<script>
    //utility function to convert the string shortcode to wp.media selection
    function select(shortcode) {
        var shortcode = wp.shortcode.next('gallery', shortcode);
        var defaultPostId = wp.media.gallery.defaults.id;
        var attachments;
        var selection;

        // Bail if we didn't match the shortcode or all of the content.
        if (!shortcode) {
            return;
        }

        shortcode = shortcode.shortcode;

        if (typeof shortcode.get('id') != 'undefined' && typeof defaultPostId != 'undefined') {
            shortcode.set('id', defaultPostId);
        }

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

        selection.gallery = attachments.gallery;

        /*
         * Fetch the query's attachments, and then break ties from the query to allow for sorting.
         */
        selection.more().done(function () {
            // Break ties with the query.
            selection.props.set({
                query: false
            });
            selection.unmirror();
            selection.props.unset('orderby');
        });
        return selection;
    }
//better to use javascript-self-invoking-functions to avoid variable leaks
    (function($){
        var meta_image_frame_gallery;
        $( '#additional_image_1' ).click(function( event ) {
            console.log('d')
            event.preventDefault();

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

            if ( meta_image_frame_gallery ) {
                meta_image_frame_gallery.open();
                return;
            }

            //get the current gallery items
            var currentItems = select($('#itv_additional_image_1').val());
            // create new media frame
            // You have to create new frame every time to control the Library state as well as selected images
            meta_image_frame_gallery = 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-library',
                selection: currentItems,
                library: {
                    type: 'image'
                },
                multiple: true
            } );

            //add close event to the frame
            meta_image_frame_gallery.on('close',function() {
                //fetch the gallery state
                var controller = meta_image_frame_gallery.states.get('gallery-library');
                var library = controller.get('library');
                //get the shortcode and update the input field
                var new_shortcode = wp.media.gallery.shortcode(library).string();
                $('#itv_additional_image_1').val(new_shortcode);
            });

            //open the wp.media frame
            meta_image_frame_gallery.open();

        } );
    })(jQuery);

</script>
    </div>
    <?php
}

//save the value
function save_custom_meta_box_gallery($post_id, $post, $update)
{
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
        return $post_id;

    if(!current_user_can("edit_post", $post_id))
        return $post_id;

    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
        return $post_id;

    $slug = "post";
    if($slug != $post->post_type)
        return $post_id;

    $meta_box_text_value = "";

    if(isset($_POST["meta-box-gallery"]))
    {
        $meta_box_text_value = $_POST["meta-box-gallery"];
    }
    update_post_meta($post_id, "meta-box-gallery", $meta_box_text_value);
}

add_action("save_post", "save_custom_meta_box_gallery", 10, 3);

如果您发现压倒性的,可以尝试ACF Gallery module

中的ACF plugin

答案 1 :(得分:2)

请试试下面的代码:

<强> jQuery的:

$(document).ready( function(){
    var meta_image_frame_gallery;
    $( '#additional_image_1' ).click(function( event ) {
        event.preventDefault();

        if ( meta_image_frame_gallery ) {
            meta_image_frame_gallery.open();
            return;
        }

        // create new media frame
        // You have to create new frame every time to control the Library state as well as selected images
        meta_image_frame_gallery = 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-library',
            library: {
                type: 'image'
            },
            multiple: true,
        } );

        /* Add image gallery shortcode in itv_additional_image_1 input filed when close event call */
        meta_image_frame_gallery.on('close',function() {
            //fetch the gallery state
            var controller = meta_image_frame_gallery.states.get('gallery-library');
            var library = controller.get('library');
            //get the shortcode and update the input field
            var new_shortcode = wp.media.gallery.shortcode(library).string();
            $('#itv_additional_image_1').val(new_shortcode);
        });

        /* Update event for image gallery */
        meta_image_frame_gallery.on('update', function () {
            var controller = meta_image_frame_gallery.states.get('gallery-edit');
            var library = controller.get('library');
            var new_shortcode = wp.media.gallery.shortcode(library).string(); // Get the new/updated shortcode here.
            $('#itv_additional_image_1').val(new_shortcode);
        });
    });
});

代码在完美的工作中经过测试。更新图库项目也很完美。