Make WordPress Core

Opened 10 years ago

Closed 9 years ago

#32180 closed enhancement (fixed)

Make link generation in wplink.js extendable

Reported by: martinsachse's profile martinsachse Owned by: sergeybiryukov's profile SergeyBiryukov
Milestone: 4.3 Priority: normal
Severity: normal Version:
Component: Editor Keywords: has-patch
Focuses: javascript, administration Cc:

Description

It should be possible to extend the html that is generated by /wp-includes/js/wplink.js.js in the htmlUpdate-method.

The solution that I am suggesting is the following. Seperate the generation of the opening a-tag (lines 293-300) into its own method e.g.

wpLink = {
  ...
  buildHtml: function(attrs) {
    var html = '<a href="' + attrs.href + '"';

    if ( attrs.target ) {
      html += ' target="' + attrs.target + '"';
    }

    return html + '>';
  }
  ...
}

This would make it possible to extend the generated opening a-tag the following way:

(function() {
  var buildHtml = wpLink.buildHtml;

  wpLink.buildHtml = function() {
    var html = buildHtml.apply(this, arguments);

    html = html.replace('>', ' data-custom-attribute="my-data">');

    return html;
  }
}());

The advantage of this method is that more than one plugin can extend the generation. Current solutions overwrite the complete wplink.js which will not work if more than one plugin try to extend the generation. It is also a problem if anything changes in the wplink.js with an update.

Possible use cases for this change:

  • Plugin that extends the link-dialog with a nofollow-option
  • Plugin that extends the link-dialog with a select for classnames
  • Plugin that lets you configure custom classes for domains. e.g. every link to example.com gets the class example

Attachments (1)

patch.diff (1.1 KB) - added by martinsachse 10 years ago.
suggested patch

Download all attachments as: .zip

Change History (6)

@martinsachse
10 years ago

suggested patch

#1 @SergeyBiryukov
10 years ago

  • Keywords has-patch added
  • Milestone changed from Awaiting Review to 4.3

#2 @Otto42
10 years ago

Agreed, I ran into this same problem.

The htmlUpdate function is currently the main problem here. All the rest of the functions in here can be overridden and the originals called to do their job, but because htmlUpdate both builds the link and inserts it into the textarea, it's not possible to easily modify the resulting link without overriding this whole function. At least, not without using silly self-modifying-code methods.

#3 @iseulde
10 years ago

wp.html.string could be useful here.

#4 @obenland
10 years ago

  • Owner set to SergeyBiryukov
  • Status changed from new to assigned

#5 @wonderboymusic
9 years ago

  • Resolution set to fixed
  • Status changed from assigned to closed

In 32802:

Add a class method to wpLink, buildHtml(). This will allows devs to duck-punch the implementation.

Props martinsachse.
Fixes #32180.

Note: See TracTickets for help on using tickets.