How to use wpLink without editor?

The question:

I would like to create theme option to add a link.
Loading these scripts and triggering the dialog works fine if wp editor is present.

wp_enqueue_script('wplink');
wp_enqueue_script('wpdialogs');
wp_enqueue_script('wpdialogs-popup');
wp_enqueue_style('wp-jquery-ui-dialog');
wp_enqueue_style('thickbox');

wp_editor('', 'unique_id', array('editor_class'=>'hidden'));



$('.add-link').on("click", function(e){
    e.preventDefault();

      wpLink.open();
      return false;
});

but how to make it open link dialog box without editor being present?

This is what I am after

How to use wpLink without editor?
enter image description here

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

There is not ethical way of doing this. But still there is a way to do this. WordPress wrote wpLink script keeping in mind that editor is there but still WordPress handle when editor is not there (Good Thing)

Consider this example and assume that we are using it on front-end in footer.

First enqueue the essential style and scripts.

function enqueue_scripts_209490() {
    wp_enqueue_script('wplink');
    wp_enqueue_style( 'editor-buttons' );
}
add_action('wp_enqueue_scripts', 'enqueue_scripts_209490');

Now hook this function in footer Read the inline comments

function display_wplink_html_209490() {
    //Our textarea, click to open the link edior and insert the link in same editor
    echo '<textarea id="example_209490"></textarea>';

    // Require the core editor class so we can call wp_link_dialog function to print the HTML.
    // Luckly it is public static method ;)
    require_once ABSPATH . "wp-includes/class-wp-editor.php";
    _WP_Editors::wp_link_dialog(); ?>

    <script type="text/javascript">
        /* We need ajaxurl to send ajax to retrive links */
        var ajaxurl = "<?php echo admin_url( 'admin-ajax.php'); ?>";
        jQuery(document).ready(function (){
            jQuery('#example_209490').click(function (){
                wpLink.open('example_209490'); /* Bind to open link editor! */
            });
        })
    </script><?php
}
add_action('wp_footer', 'display_wplink_html_209490');

Note: It will not work when user is not logged-in because of js error
setUserSetting is not defined and no AJAX response when user not
logged-in.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment