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

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

我在元字段上创建了一个图库媒体上传程序。它工作完美。

当我点击 Browse 时,画廊媒体上传器打开,我 select 图片然后点击 Insert Gallery 但我没有得到画廊的简码在输入元字段中。

这是我从互联网上获得的代码:

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

    } );

这是我的 html 代码:

<input id="itv_additional_image_1" class="input-text" name="itv_additional_image_1" placeholder="" type="text">
<input id="additional_image_1" name="additional_image_1" value="Browse" type="button">

我jquery很弱,所以请指导我这个问题

你需要

  • 为 wp.media 帧添加一个 'close' 事件
  • 从关闭事件中的 wp.media 获取短代码并将其传递给输入
  • 当post为saved/published
  • 时,在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 from ACF plugin

你能试试下面的代码吗:

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

代码已经过测试,工作完美。更新图库项目也很完美。