External URL's
You will have to grab the contents of the webpage, and grab the title out of it. Be wary of this though as it can significantly slow down the loading speed of your page depending on how many links you are trying to grab and how long their servers take to pass the content.
Doing this also requires you to parse HTML with regex which is generally something to avoid.
This is what the end result will look like:
function shortcode_out($atts) {
$atts = shortcode_atts( array(
'link' => '/',
'newtab' => false
) , $atts);
//get the URL title
$contents = file_get_contents($atts['link']);
if ( strlen($contents) > 0 ) {
$contents = trim(preg_replace('/\s+/', ' ', $contents));
preg_match("/\<title\>(.*)\<\/title\>/i", $contents, $title);
$site_title = $title[1];
} else {
$site_title = 'URL could not be found';
}
if ($atts['newtab'] == true)
return '<a target=_blank href='.$atts['link'].'>'.$site_title.'</a>';
else
return '<a href='.$atts['link'].'>'.$site_title.'</a>';
}
Internal URL's
If you want to grab an internal URL, then there's actually a WordPress function that can handle this for you: url_to_postid()
. Once you have the post ID, you can use get_the_title()
to retrieve the post title like this:
$post_id = url_to_postid($url);
$title = get_the_title($post_id);
This is what the end result would look like:
function shortcode_out($atts) {
$atts = shortcode_atts( array(
'link' => '/',
'newtab' => false
) , $atts);
//get the post title
$post_id = url_to_postid($atts['link']);
$title = get_the_title($post_id);
if ($atts['newtab'] == true)
return '<a target=_blank href='.$atts['link'].'>'.$title.'</a>';
else
return '<a href='.$atts['link'].'>'.$title.'</a>';
}
url_to_postid
will return int(0)
if it can't resolve the URL, so if you wanted to be extra careful, you could always change the $title
variable to check first like this:
$title = ($post_id ? get_the_title($post_id) : 'Post could not be found');