在给定 URL 作为自定义短代码参数的情况下,如何读取外部页面的标题?

How can I read the title of an external page given the URL, as parameter, in a custom shortcode?

我想显示 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>';
}

我怎样才能做到这一点?

外部URL的

您将必须抓取网页的内容,并从中抓取标题。请注意这一点,因为它会显着降低页面的加载速度,具体取决于您尝试获取的链接数量以及服务器传递内容所需的时间。

这样做还需要您使用 generally something to avoid.

的正则表达式解析 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的

如果您想获取内部 URL,那么实际上有一个 WordPress 函数可以为您处理此问题:url_to_postid(). Once you have the post ID, you can use get_the_title() 检索 post 标题,如下所示:

$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 将 return int(0) 如果它不能解析 URL,所以如果你想格外小心,你可以随时更改 $title 像这样首先检查的变量:

$title = ($post_id ? get_the_title($post_id) : 'Post could not be found');