将外部网页嵌入/链接到我的WordPress博客(如Facebook Grabs图像、标题和描述)

时间:2016-11-06 作者:Jamal

我想在嵌入外部页面的地方创建WordPress帖子。正如您所知,当您在Facebook中粘贴链接时,它会自动获取图像、标题和描述。当有人点击它时,它会指向源网站。我使用了iframes,但它嵌入了整个页面。我只想把它显示在Facebook共享中。我想在我的主页上聚合来自网络各地的新闻。如果我可以添加用户对故事投票的功能,这将是一个额外的优势。附言:我不是程序员。Example

1 个回复
SO网友:jgraup

看起来你可能在描述embeds WordPress支持的。在…上https://codex.wordpress.org/Embeds 您将根据编辑器中添加的URL找到一长串当前支持的嵌入。

为了使嵌入工作,需要在一行上下各有一个空格。通常在the_content 滤器

要测试当前支持哪些嵌入,可以使用wp_oembed_get($url).

有两种方法可用于添加对当前未包含的嵌入的支持。

对于非嵌入式站点-wp_embed_register_handler( $id, $regex, $callback, $priority )对于启用oEmbed的站点-wp_oembed_add_provider( $format, $provider, $regex ).如果没有包含站点,则可能需要编写将URL转换为嵌入所需的正则表达式。但在那之后,它会像魔术一样工作。

给出了一个在不受支持的oEmbed站点上自定义嵌入的示例(修改自@birgire\'s answer):

/**
 * Embed support for Forbes videos
 *
 * Usage Example:
 *
 *     http://www.forbes.com/video/5049647995001/
 */
add_action( \'init\', function()
{
    wp_embed_register_handler(
        \'forbes\',
        \'#http://www\\.forbes\\.com/video/([\\d]+)/?#i\',
        \'wp_embed_handler_forbes\'
    );

} );

function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr )
{
    // construct the video embed

    $embed = sprintf(
        \'<iframe class="forbes-video" src="https://players.brightcove.net/2097119709001/598f142b-5fda-4057-8ece-b03c43222b3f_default/index.html?videoId=%1$s" width="600" height="400" frameborder="0" scrolling="no"></iframe>\',
        esc_attr( $matches[1] )
    );

    // pull information from the page

    $str = wp_remote_retrieve_body(wp_remote_get($url));
    preg_match_all(\'/<head>(?:[^<]+)<title>([^<]+)<\\/title>/\', $str, $matches);
    $title = @$matches[1][0];
    preg_match_all(\'/<meta name="description" itemprop="description" content="([^"]+)"/\', $str, $matches);
    $description = @$matches[1][0];
    preg_match_all(\'/<meta property="og:image" content="([^"]+)"/\', $str, $matches);
    $image = @$matches[1][0];

    // prepend extra info

    $embed = sprintf(\'<a href="%s" target="_blank" rel="noopener noreferrer" ><img src="%s"><h1>%s</h1></a><p>%s</p>%s\', $url, $image, $title, $description, $embed);

    return apply_filters( \'embed_forbes\', $embed, $matches, $attr, $url, $rawattr );
}
样品包括:

http://www.forbes.com/video/5049647995001/

http://www.forbes.com/video/5037500512001/

http://www.forbes.com/video/4284088649001/

http://www.forbes.com/video/5046852474001/
虽然此示例专门使用iframe 您可以从url构造任何内容。这需要额外的时间,但从理论上讲,您可以提取URL并获取详细信息来定制视觉效果。

对于Facebook,他们使用一项服务http://developers.facebook.com/tools/lint/ 缓存刮取的内容,然后提供缓存的数据。这就是为什么有时页面的第一部分需要一段时间才能显示出来。如果您想加快这个过程,您将有一种机制来缓存要提供的内容。

相关推荐

oembed_cache SPAM problem

我最近在查看我的数据库时发现了数百篇带有post\\u类型oembed\\u缓存的帖子。其中许多似乎是垃圾邮件。我一辈子都搞不清楚这些数据是如何被注入我的数据库的。这是phpmyadmin的照片LINK. 还有其他人有这个问题吗?有人能提供一些见解吗?我该如何清理,更重要的是,我该如何防止它的发生?