14

Is there a hook / filter to process the link being added into a WordPress post ?

My aim is to pre-process the link inserted in a post using the following button and shorten it using a third party API like bit.ly

I want to do this for both internal / external links.

TinyMCE add link button

One solution that I an think of is to add an extra button to my editor that does this but I would prefer a hook / filter that does the job, that way it would be more clean and I will convert that into a custom plugin for my website (there by allowing my WordPress to be up-gradable).

I went through the WordPress docs and skimmed through the following hooks / filters which were of no use to me

  1. https://developer.wordpress.org/reference/hooks/add_link/

  2. https://developer.wordpress.org/reference/hooks/post_link/

  3. And most of the ones listed here https://developer.wordpress.org/?s=link

4 Answers 4

13
+100

Update 1: As far as I know, external URLs are inserted into post content by TinyMCE editor link plugin, PHP does nothing.

In WordPress, there're two plugins which located at wp-includes/js/wplink.js and wp-includes/js/tinymce/plugins/wplink/plugin.js. Note that if you're not in SCRIPT_DEBUG mode, they have .min suffix.

  1. wp-includes/js/wplink.js handles this dialog:

wplink dialog box 1

To filter URLs inserted via this dialog box, we must override wpLink.getAttrs method. For example, to add so39115564 string to every URLs:

jQuery(document).ready(function($) {
  wpLink.getAttrs = function() {
    wpLink.correctURL();
    return {
      href: $.trim( $("#wp-link-url").val() + "so39115564" ),
      target: $("#wp-link-target").prop("checked") ? "_blank" : ""
    };
  }
});

You should take a look at the wp-includes/js/wplink.js for more info. It's too long to explain in detail here.

And let say the above script is mylink.js, here is how we should enqueue it:

add_filter('admin_enqueue_scripts', function()
{
  // { Maybe some conditions for a valid screen here. }

  wp_enqueue_script('mylink', 'link/to/the/mylink.js', ['link'], '1.0', true);
}, 0, 0);
  1. wp-includes/js/tinymce/plugins/wplink/plugin.js handles this dialog:

wplink dialog 2

This time, we also have to override setURL method of tinymce.ui.WPLinkPreview. But, it's almost impossible, unless you deregister this script and register a modified version. Then manage that script yourself with unpredictable changes from WordPress.

Now, choose it wisely! Shorten any external URLs before pasting them into your posts or mess up with WordPress TinyMCE plugins or use dialog box of wp-includes/js/wplink.js plugin.


Yes! WordPress inserts inline links via wp_link_ajax action which is executed by wp_ajax_wp_link_ajax() function.

As you can see in source code of that function, $results is retrieved by _WP_Editors::wp_link_query. Check out this method, you will meet wp_link_query filter. This filter accept two arguments: $results and $query. $results will be what we need to filter.

For example, we need to append so39115564 to the queried link:

add_filter('wp_link_query', function(array $results, array $query)
{
  $results[0]['permalink'] = $results[0]['permalink'] . 'so39115564';

  return $results;
}, PHP_INT_MAX, 2);

Now, you should know how to do it. Make sure to take a look at _WP_Editors::wp_link_query to filter the $results more efficient.

4
  • While this works for internal linking of posts this only serves as a partial answer. As it is possible to paste an external link as well into the link text box. External link does not call this filter. Up voted for partial answer, will wait for a complete answer or else will accept this in 7 days.
    – divyenduz
    Aug 27, 2016 at 8:17
  • @divyenduz I have just updated the answer. Hope you can find out the best way!
    – wpclevel
    Aug 27, 2016 at 13:37
  • 1
    I ended up using wp_insert_post_data and wp_link_query. For external links, filtered post content before saving. Thanks, I will accept this answer after waiting for 2 days for another answer.
    – divyenduz
    Aug 28, 2016 at 6:20
  • I've used this approach and it's a great one. Just adding: wp_link_query_args is another filter for the same _WP_Editors::wp_link_query that let you alterate query params before they're used to query the DB. Ref: codex.wordpress.org/Plugin_API/Filter_Reference/… Jun 4, 2019 at 15:16
1

Have you considered not processing the link until you save the post? There is an action in the wordpress plugin api called "save_post" that's triggered on save.

Using "save_post" you could parse the content of the post and replace links using a url shortener then.

https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

3
  • I considered that alternative as well but my posts will have many short links (30-50). Doing that in one go will make save_post very slow.
    – divyenduz
    Aug 24, 2016 at 7:49
  • @divyenduz I think save_post would be the easiest solution considering that making a extra button in the editor requires a tinymce plugin that can be a lot of work to make.
    – lassemt
    Aug 24, 2016 at 9:26
  • Thanks, will use this method in case I am unable to find any other solution and mark your answer complete. Will give this question some time though.
    – divyenduz
    Aug 24, 2016 at 10:14
1

There might be plugins available for this , but here is the default logic behind.

1st Way : To save the shortened URL in DB also

add_action( 'save_post', 'save_book_meta', 10, 3 );
function save_book_meta( $post_id, $post, $update ) {
    global $wpdb;
    $slug = 'event';

    // If this isn't a 'book' post, don't update it.
    if ( $slug != $post->post_type ) {
        return;
    }

    preg_match_all('|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i', $post->post_content, $match);

    $new_content = $post->post_content;

    foreach($match[1] as $link){
        $url = 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAnw98CCy5owhpgB2HvW3SkoXfm0MrLjks';

        $json_data = json_encode( array( 'longUrl' => $link ) );

        //open connection
        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        curl_close($ch);


        $result = json_decode($result);
        $new_content = str_replace($link, $result->id, $new_content);

    }

    // unhook this function so it doesn't loop infinitely
    remove_action('save_post', 'save_book_meta' );

    $post_new = array(
        'ID'       => $post_id,
        'post_content'  => $new_content
      );

    $post_id = wp_update_post( $post_new, true );                         
    if (is_wp_error($post_id)) {
        $errors = $post_id->get_error_messages();
        foreach ($errors as $error) {
            echo $error;
        }
    }
    add_action( 'save_post', 'save_book_meta' );

}

To achieve the above thing you will have to do following things :

  • Use save_post hook to get the post content after saving.
  • In this hook fetch all the external links in an array (modify the conditions as per requirements).
  • Shorten the URL by using google API (key is required).
  • Get response from the Google API and update the post_data accordingly in the database also.
  • At wp_update_post we are removing the hook to avoid infinite loop.

2nd Way : To show the front-end user shortened URL , (DB will have longUrl though)

  • Use the filter hook instead and with the same logic.

3rd Way : Plugin Usage (Not used personally).

1

I am not perfect in TinyMCE because i didn't used TinyMCE in several project but i have experience with javascript so i found a some TinyMCE event api to use you can make a short url. I checked in WP latest version and TinyMCE version 4.x. You can also find for right api to trigger your custom callback.

Before tinymce initialize in wordpress editor register setup function using wordpress hook tiny_mce_before_init.

add_filter( 'tiny_mce_before_init', 'my_plugin_tiny_mce_before_init' );
function my_plugin_tiny_mce_before_init( $in ){
  $in['setup'] = 'myplugin_tinymce_setup'; // javascript callback 
  return $in;   
}

   add_action( 'admin_footer', 'add_admin_footer' );

After add javascript callback in admin footer. I have two methods for this solution.

#1 method

function add_admin_footer(){
 ?>
  <script type="text/javascript">
    var counter = 1, insert_url, shorten_url;

    function myplugin_tinymce_setup( editor ){

     editor.onNodeChange.add(function(ed, cm, e) {
          // Activates the link button when the caret is placed in a anchor element
          if (e.nodeName.toLowerCase() == 'a'){
            var element = jQuery(e).not('a[href="_wp_link_placeholder"],a[data-wplink-edit="true"]');
            if( element.length ){
              if( is_shorten = getShortenUrl( element.attr( 'href') ) ){ 
               element.attr( 'href', is_shorten );
               element.attr( 'data-mce-href', is_shorten );
              }
            }
          }

      });

 var hostname = new RegExp(location.host);
    var shorten_host = new RegExp('http://www.example.com'); // enter your short url generate host name
    function getShortenUrl( url ){
        // add more condition here...
        // Add here ajax or shorten javascript api etc.
        // filter and return short url
        if( hostname.test( url ) ){
           // internal link  
           // Return internal url with shorten
           return 'http://www.example.com/Internal/'+counter++;     

        }else if( shorten_host.test( url ) ){
          // not update already update with shorten url
          return false; 

        }else{
          // Return external url with shorten
          return 'http://www.example.com/External/'+counter++;  
        }

    }
</script>
 <?php  

WP link shorten in editor

#2 method

function add_admin_footer(){
 ?>
  <script type="text/javascript">
    var counter = 1, insert_url, shorten_url;

    function myplugin_tinymce_setup( editor ){

        editor.on('ExecCommand', function(e) {

            // Eexcute command when click on button apply on insert/edit link
           if( e.command == 'wp_link_apply' ){

              if( editor.selection.getContent() ){
                element = tinymce.$(editor.selection.getContent()); // Create new link 
              }else{
                element = tinymce.$(editor.selection.getNode()); // Edit link option 
              }
              if( element.prop('tagName').toLowerCase() == 'a' ){
                  current_link_url = element.attr('href'); // Real url added in editor.
                  // and also check current_link_url is not shorten url
                  // add more logic here. Get short url using ajax or bitly javascript api. 
                  if( is_shorten_url = getShortenUrl( element.attr('href')) ){
                    editor.execCommand('mceInsertLink',false,{ href: is_shorten_url });  
                  }

              }
           }

        });
    }

    var hostname = new RegExp(location.host);
    var shorten_host = new RegExp('http://www.example.com'); // enter your short url generate host name
    function getShortenUrl( url ){
        // add more condition here...
        // Add here ajax or shorten javascript api etc.
        // filter and return short url
        if( hostname.test( url ) ){
           // internal link  
           // Return internal url with shorten
           return 'http://www.example.com/Internal/'+counter++;     

        }else if( shorten_host.test( url ) ){
          // not update already update with shorten url
          return false; 

        }else{
          // Return external url with shorten
          return 'http://www.example.com/External/'+counter++;  
        }

    }

  </script>
 <?php  

}

Best of luck :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.