[WordPress Snippet] Get first image from content

1
2
3
4
5
6
7
8
9
10
11
12
13
function get_first_image_from_content($content) {
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('//i', $content, $matches);
    $first_img = $matches [1] [0];

    if(empty($first_img)) {
        $first_img = get_template_directory_uri() . "/images/default.jpg";
    }

    return $first_img;
}