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

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 に答える
0

私はいくつかのテストを行い、最終的に問題を解決しました。間違いかどうかはわかりませんが、コードは同じで、正しく動作するようになりました。ありがとう。

于 2012-08-06T13:34:19.787 に答える