1

How do I make URL auto recognized and changed to href html form in wordpress.

If I post:

http://stackoverflow.com/

I want it to automaticly go to:

<a href="http://stackoverflow.com/" target="_blank">My Text</a>
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Mr.Jenkins
  • 43
  • 1
  • 7

2 Answers2

2

You could do this with jQuery but if it when wrong/slow loading on page might yield odd results so your best bet is to us something like this in PHP

<?php
$url_pattern = "@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@";
$text = "This is my text, it make include a link like http://google.com or http://www.bbc.co.uk";
$replace = '<a href="$1" target="_blank">$1</a>';
$text = preg_replace($url_pattern, $replace, $text);
echo $text;
?>

You could set this into a little function and apply it as a filter to content before/as you output it onto your page(s) etc.

Harry Finn
  • 742
  • 4
  • 10
  • Great. Harry, how to now remove filter in one function only. I added add_filter( 'the_content', 'url_auto' );, Now, I just need to remove filter inside shortcodes, or inside one function, how is easier. Answer accepted anyway. – Mr.Jenkins Jul 09 '13 at 22:10
  • Sorry, I don't quite understand - Are you saying you only want to apply this url filter to a particular shortcode, or just all shortcodes in general (and not on the_content) - let me know and I'll try to help further! – Harry Finn Jul 09 '13 at 22:35
  • I applied it to the_content. I want to remove it inside shortcodes. – Mr.Jenkins Jul 09 '13 at 22:39
  • At first I thought this will work, but now I see it always outputs same instead of link:"This is my text, it make include a link like http://google.com or http://www.bbc.co.uk". – Mr.Jenkins Jul 09 '13 at 23:43
  • Yes of course it always outputs the same as $text is defined with that example above, you need to change this in your function. Simply set it up as a function with the $text variable as the item passed into the function i.e. `function convert_urls($text) { //rest of code goes here }` and remember to remove the $text = "this is my text, ...." etc from the function, this way you can pass text/content to the function and filter it with either a string variable or something like get_the_content() in wordpress – Harry Finn Jul 09 '13 at 23:56
  • See this = http://wordpress.stackexchange.com/questions/13810/adding-a-filter-to-a-shortcode - For applying a filter to a shortcode(s) – Harry Finn Jul 10 '13 at 00:00
  • Ok. I got it. Just now with $url_pattern works untill dash, when dash appears in url, it will stop there and link is not correct. – Mr.Jenkins Jul 10 '13 at 00:10
0

There are plugins available to do this in WordPress if you don't want to do it programmatically. Here are a couple:

Bill Rollins
  • 1,736
  • 1
  • 12
  • 18