我想显示在我的自定义短代码插件中作为参数给出的 URL 页面的标题(例如:https://www.google.it/)。这是我的代码:
function shortcode_out($atts) {
$atts = shortcode_atts( array(
'link' => '/',
'newtab' => false
) , $atts);
if ($atts['newtab'] == true)
return '<a target=_blank href='.$atts['link'].'>'.{GET_TITLE_OF_$atts['link']}.'</a>';
else
return '<a href='.$atts['link'].'>'.{GET_TITLE_OF_$atts['link']}.'</a>';
}
我怎样才能做到这一点?
您将不得不抓取网页的内容,并从中抓取标题。但请注意这一点,因为它会显着降低页面的加载速度,具体取决于您尝试获取的链接数量以及他们的服务器传递内容所需的时间。
这样做还需要您使用正则表达式解析 HTML,这通常是需要避免的。
这就是最终结果的样子:
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>';
}
如果您想获取内部 URL,那么实际上有一个 WordPress 功能可以为您处理:url_to_postid()
. 获得帖子 ID 后,您可以get_the_title()
像这样检索帖子标题:
$post_id = url_to_postid($url);
$title = get_the_title($post_id);
这就是最终结果的样子:
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
int(0)
如果它无法解析 URL,它将返回,因此如果您想格外小心,您可以随时更改$title
变量以首先检查,如下所示:
$title = ($post_id ? get_the_title($post_id) : 'Post could not be found');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句