WEBTODESIGN

WordPressで記事の最初の画像をサムネにして、それもない場合は代替画像を表示する

記事の最初の画像をサムネにして、それもない場合は代替画像を表示したい。

functions.phpに以下を記述。

function thumnail() {
    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)){
        $first_img = get_template_directory_uri() .'/img/noimg.jpg';
    }
    return $first_img;
}

特に、画像がない場合の「get_template_directory_uri()」の部分。あらゆるブログでこれがなくて、画像が表示されなくて非常に困惑した、、、。

そして表示したいループの中に以下のように記述。

<img src="<?php echo thumnail(); ?>" alt="<?php the_title(); ?>">

ほあ〜!サムネ設定してないけどサムネが表示された。