WP/PHP函数提取的图像没有';不起作用


WP / PHP function to extract the image doesn't work

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

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属性,但它是空的。

有人能帮我吗?感谢

您是否执行了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;
        }
    }

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