LoginSignup
10
11

More than 5 years have passed since last update.

WordPress でポスト本文に記述された最初の画像URLを取得

Last updated at Posted at 2013-06-12

手順.1

適用するテーマの functions.php に関数を追加

function view_first_image_src() {
    global $post, $posts;
    $_first_img_src = '';

    ob_start();
    ob_end_clean();

    $_output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $_matches);

    $_first_img_src = $_matches[1][0];

    if(empty($_first_img_src)){
        // 画像を含まない場合のカバー
        $_first_img_src = "/img/common/no-img.png";
    } else {
        // マルチサイト向けにWP インストールディレクトリへURLを書き換え
        $_img_src_arr = explode('/wp-content/', $_first_img_src);
        $_first_img_src = '/hoge/wp-content/' . $_img_src_arr[1];
    }

    return $_first_img_src;
}

if(empty($_first_img_src)) の else 文は、お好みで。

手順.2

表示先のループ内で、関数を実行

<img src="<?php echo view_first_image_src(); ?>" />
10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11