Use WordPress link insert dialog in metabox?

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?

Related posts

Leave a Reply

1 comment

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

    Make sure you have enqueued wp-link

    1 / wp_enqueue_script( 'wp-link' );

    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 / Invoke link dialogue

    $('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 / Handle link saves

    $('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 / Handle link cancels

        $('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;
        });
    

    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.