How to get shortcode of wp gallery on creating gallery in meta field

落爺英雄遲暮 提交于 2019-12-07 01:44:28

Can you please try below code:

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);
        });
    });
});

Code is tested in work perfect. update gallery item also work perfect.

you need to

  • add an 'close' event for the wp.media frame
  • fetch the shortcode from the wp.media inside the close event and pass it to the input
  • add a save_action hook on the wordpress to save this value when post is saved/published
  • additionally you may need to fetch the current gallery items from the input and pass it to the wp.media frame, so that use can see the previously selected image.

You can use the following working code and test on your WordPress installation.

//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);

If you find this overwhelming you can try ACF Gallery module from ACF plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!