Pages

Tuesday, September 4, 2012

Get the first image or video from a post - [resolved]


The function returns an image/video and must be called inside the loop.

function show_thumb() {
    global $post, $posts;
    $thumb = '';
    ob_start();
    ob_end_clean();
    // filter video
    $output = preg_match_all('/(\<object.*\<\/object\>)/is', $post->post_content, $matches);
    if($output == ''){    $output = preg_match_all('/(\<iframe.*\<\/iframe\>)/is', $post->post_content, $matches);    }
    if($matches[1][0] != '')    {    $thumb = $matches[1][0];} else { $thumb = ''; }
    if(empty($thumb)) { // no video tags found, filter wordtube tag instead
        $output = preg_match_all('/\[media id=(.*?)]/i', $post->post_content, $matches);
        $thumb = $matches[1][0];
        if (empty($thumb)) { // no wordtube tags, search for images instead
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
            $thumb = $matches[1][0];
            if(empty($thumb)) { // no images found, use a default image
                $postlist_id = $post->ID;
                    $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $postlist_id ), "medium");
                    $myimage = $imgsrc[0];
                    if($myimage != '')
                    {
                        $thumb = '<img src="'.$myimage.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" style="width:150px; border: 1px solid #cccccc; padding: 2px;"/>';
                    }
            } else {  // image found, return image
                $thumb = '<img src="'.$thumb.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" style="width:150px; border: 1px solid #cccccc; padding: 2px;"/>';
            }
        }else { //  wordTube tag found, execute shortcode
            $thumb = '[media id=' . $thumb . ']';
            $thumb = apply_filters('the_content', $thumb );
        }
    }
    return $thumb;
}

No comments: