在metabox中使用WordPress链接插入对话框?

use*_*281 8 wordpress

我经常使用自定义元变量.通常我会在元数据库中有一个"链接"字段.我一直在使用一个简单的文本输入字段,但我想弄清楚如何放入一个按钮,它会调用WordPress内容编辑器使用的相同"插入链接"对话框.那可能吗?

nop*_*ies 15

您可以先调用所需的js,然后与wp-link js文件方法进行交互,从而调用链接框.

确保你已经排队wp-link

1/wp_enqueue_script( 'wp-link' );

2 /设置你的用户界面.我通常使用一个按钮来调用链接对话框和一个文本字段来处理链接URL.

3 /调用链接对话

$('body').on('click', '.link-btn', function(event) {
            wpActiveEditor = true; //we need to override this var as the link dialogue is expecting an actual wp_editor instance
            wpLink.open(); //open the link popup
            return false;
        });
Run Code Online (Sandbox Code Playgroud)

4 /处理链接保存

$('body').on('click', '#wp-link-submit', function(event) {
            var linkAtts = wpLink.getAttrs();//the links attributes (href, target) are stored in an object, which can be access via  wpLink.getAttrs()
            $('your_url_textfield').val(linkAtts.href);//get the href attribute and add to a textfield, or use as you see fit
            wpLink.textarea = $('body'); //to close the link dialogue, it is again expecting an wp_editor instance, so you need to give it something to set focus back to. In this case, I'm using body, but the textfield with the URL would be fine
            wpLink.close();//close the dialogue
//trap any events
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
            event.stopPropagation();
            return false;
        });
Run Code Online (Sandbox Code Playgroud)

5 /句柄链接取消

    $('body').on('click', '#wp-link-cancel, #wp-link-close', function(event) {
        wpLink.textarea = $('body');
        wpLink.close();
        event.preventDefault ? event.preventDefault() : event.returnValue = false;
        event.stopPropagation();
        return false;
    });
Run Code Online (Sandbox Code Playgroud)

应该做的.我在metabox类中使用相同的方法,它似乎工作正常.因为我正在硬编码对链接对话框的html元素的引用.对话确实需要一个外部API.可能并不是很难添加到WP.