在 metabox 中使用 WordPress 链接插入对话框? [英] Use WordPress link insert dialog in metabox?

查看:16
本文介绍了在 metabox 中使用 WordPress 链接插入对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用自定义元框.我经常会在元框中有一个链接"字段.我一直在使用一个简单的文本输入字段,但我试图弄清楚如何放置一个按钮,该按钮将调用与 WordPress 内容编辑器使用的相同的插入链接"对话框.这可能吗?

I use custom metaboxes quite frequently. Very often I will have a "link" field in a metabox. I've been using just a simple text input field, but I'm trying to figure out how to put in a button that would call the same "insert link" dialog that the WordPress content editor uses. Is that possible?

推荐答案

您可以通过先将所需的 js 入队,然后与 wp-link js 文件方法交互来调用链接框.

You can invoke the link box by first enqueing the required js, and then interacting with the wp-link js files methods.

确保您已将 wp-link 加入队列

Make sure you have enqueued wp-link

1/wp_enqueue_script('wp-link');

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

2 / Set up your ui. I usually use a button to invoke the link dialogue from and a textfield to handle the links 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;
        });

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

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

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

Should about do it. I use the same approach in my metabox class and it seems to work OK. Its abit of a hack, as I'm hardcoding references to the link dialogue's html elements. The dialogue does need an external API. Probably not all that hard to add to WP.

这篇关于在 metabox 中使用 WordPress 链接插入对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆