wordpress插件开发通过js调用图库/媒体选择器的问题

650次阅读
没有评论

最近开发一个插件,遇到了这个问题:wordpress插件开发时如何通过js调用图库/媒体选择器的问题

最终效果:

wordpress插件开发通过js调用图库/媒体选择器的问题

 

先总结:

  1. 在add_action的回调里执行wp_enqueue_media()注入
  2. 使用wp.media().open()打开媒体选择器了
  3. 监听第2步返回的selector对象的select事件执行selector.state().get(‘selection’).first().attributes就可以获取到选择的文件了
  4. 使用第2步返回的selector对象的close方法关闭媒体选择器

给个例子:

php里注入:

add_action('admin_menu', 'seekstack_collector_menu_init');

function seekstack_collector_menu_init(){
    add_menu_page(
        SH_PageTitle,
        SH_MenuTitle,
        'administrator',
        SH_Tag, 
        'seekhub_collector_menu_callback',
        'dashicons-image-flip-horizontal',
        40
    );
}

function seekhub_collector_menu_callback(){
    wp_enqueue_media();  // 在这里注入

    include_once(SH_Plugin_DIR.'home.php');
}

javascript里调用:

$('#watermark_img a').on('click', function(){
            // 打开媒体选择器
            var selector = wp.media({
		// Set the title of the modal.
		title: '选择水印',
                // Customize the submit button.
		    button: {
			// Set the text of the button.
			text: '确认',
			// Tell the button not to close the modal, since we're
			// going to refresh the page when the image is selected.
				close: false
			}
	    }).open();

            selector.on('select', function(){
                var file = selector.state().get('selection').first().attributes;

                if(file.width > 200 || file.height > 200){
                    alert('你选择的图片尺寸过大,不适合做水印');
                    return;
                }
                
                console.log(file);
                $('#watermark_img input').val(file.url);
                $('#watermark_img a').html('<img src="' + file.url + '" />');

                selector.close();   // 关闭选择器 
            })
        })

后话:

要使用wordpress的媒体选择器就需要用到wp.media对象,而要用这个对象必须先在插件里wp_enqueue_media()注入相关前端资源,弄清楚这个流程花了不少时间,看了别人的主题和插件的代码才搞明白,这里做个记录。

当时bing、baidu都没搜到相关资料,所幸在别人的主题和插件里找到了相关代码,nice!

4
facingscreen
版权声明:本站原创文章,由 facingscreen2022-03-05发表,共计1376字。
转载说明:本文为搜栈网原创文章,除特殊说明外皆由CC-4.0协议发布,转载请注明出处,如有帮助欢迎打赏。
评论(没有评论)
验证码