Inserting PHP is not really the way you want to do this. You would then need additional code to execute the PHP in the post body. It could be complicated.
-
Replace the links using a filter on
the_content
. Something like this:function replace_urls_wpse_91463($matches) { $ret="<a"; if (isset($matches[1])) { $ret .= $matches[1]; } if (isset($matches[2])) { $home = parse_url(get_home_url()); $url = parse_url($matches[2]); if (isset($url['host']) && $home['host'] !== $url['host']) { $link = $matches[2]; } if (!isset($url['host']) && isset($url['path'])) { $link = get_home_url('',$url['path']); } $ret .= 'href="'.$link.'"'; } if (isset($matches[3])) { $ret .= $matches[3]; } $ret .= '>'; if (isset($matches[4])) { $ret .= $matches[4]; } $ret .= '</a>'; return $ret; } function replace_urls_filter_wpse_91463($content){ $content = preg_replace_callback('/<a([^>]*)href=(?:"|\')([^"\']*)(?:"|\')([^>]*)>([^<]*)/','replace_urls_wpse_91463',$content); return $content; } add_filter('the_content','replace_urls_filter_wpse_91463',1000);
And I stress something like that, because that was put together in a hurry and will probably break in all kinds of horrible ways. And besides, parsing HTML with regex is pretty dicey even on a good day. Fun? Yes. Reliable? Not so much. I would recommend option #2. I am sure that could be cleaned up– a lot– but again, I would recommend option #2
-
Create a shortcode. Your people enter
[url link="https://wordpress.stackexchange.com/london"]London[/url]
. Something like this:function makeurl_sc_wpse_91463($atts,$content) { extract(shortcode_atts(array(),$atts)); $home = parse_url(get_home_url()); if (!isset($atts['link'])) return; $link = parse_url($atts['link']); if (isset($link['host']) && $link['host'] !== $home['host']) { $link = $atts['link']; } elseif (isset($link['path'])) { $link = get_home_url('',$link['path']); } $pat="<a href="https://wordpress.stackexchange.com/questions/91463/%s">%s</a>"; return sprintf($pat,$link,$content); } add_shortcode('url', 'makeurl_sc_wpse_91463');
Much nicer, and likely far more reliable. As before, this was put together in a hurry but it does have the minimal functionality mentioned in your question. I wouldn’t put it into production without thorough testing and debugging.