0

我经常使用这个函数来提取帖子的图像:

function first_post_image($content) {
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];
return $first_img;
}

然后我用以下代码显示图像

<?php $postimage = first_post_image(get_the_content()); ?> // catch the image
<img src="<?php echo $postimage; ?>" /> //view the image

现在我尝试在我的上一个模板(wp)中使用此功能,但图像没有出现。我可以看到标签 img 和 src 属性,但它是空的。

有人可以帮助我吗?谢谢

4

2 回答 2

0

我做了一些测试,最后我解决了这个问题。我不知道我是否犯了错误,但代码是相同的,现在可以正常工作。谢谢。

于 2012-08-06T13:34:19.787 回答
0

你有没有做过var_dump( $postimage );看看函数返回了什么?

这是一个有效的方法,如果没有图像,它不会返回一个空数组,而是返回 false,因此您可以指定备份或默认图像。

    /**
     * Extracts the first image in the post content
     *
     * @param object $post the post object
     * @return bool|string false if no images or img src
     */
    function extract_image( $post ) {
        $html = $post->post_content;
        if ( stripos( $html, '<img' ) !== false ) {
            $regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
            preg_match( $regex, $html, $matches );
            unset( $regex );
            unset( $html );
            if ( is_array( $matches ) && ! empty( $matches ) ) {
                return  $matches[2];

            } else {
                return false;
            }
        } else {
            return false;
        }
    }
于 2012-07-26T19:48:08.593 回答