Facebook Meta Tag PHP条件

时间:2012-04-17 08:57:09

标签: php facebook wordpress

我在尝试获取此代码段以便为数组中的每个图像输出单独的og:image元标记时遇到问题。

 <?php    function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
        //Defines a default image
        $first_img = "http://example.com/images/fbthumb.jpg";
    }
return $first_img;
}
 ?>

目前代码正在返回第一个匹配的img src标记,但我希望将它们全部作为单独的标记返回,以便我可以选择要使用的共享图像。

我知道这一行:

   $first_img = $matches [1] [0];

需要针对每种情况更改为某种类型,但我不确定如何。任何帮助将不胜感激。谢谢!

编辑:

这是我最后一条建议后的代码:

<?php function catch_that_image() {
global $post, $posts;
$result = preg_match_all('#<img.+src=[\'"]([^\'"]+)[^>]*>#i', $post->post_content, $matches);

return $matches[1];

}

&GT;

“/&gt;

我仍然无法弄明白。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个功能。它将返回一组图像源。然后,您可以始终将阵列中的第一个图像用作默认图像。

function catch_that_image() {
    global $post, $posts;
    $imgSources = array();
    $result = preg_match_all('#<img.+src=[\'"]([^\'"]+)[^>]*>#i', $post->post_content, $matches);

    foreach($matches[1] as $match) {
        $imgSources[] = $match;
    }

    return $imgSources;
}

或更简单

function catch_that_image() {
    global $post, $posts;
    $result = preg_match_all('#<img.+src=[\'"]([^\'"]+)[^>]*>#i', $post->post_content, $matches);

    return $matches[1];
}

使用该功能:

$imageArray = catch_that_image();
foreach($imageArray as $image) {
    echo '<meta property=​"og:​image" content=​"$image">';
}
相关问题