<?php
/********* Post Image Functions ********/

// Container function
function post_image($width = 460, $height = 170) {
global $post;
echo find_image($post->ID, $width, $height);
}

// Check custom field, otherwise use first image
function find_image($id, $width, $height) {
if (custom_image($id)) {
if (custom_image($id) != 'none') {
return timthumb(custom_image($id), $width, $height);
}
}
elseif (first_image($id)) {
if (!is_single()) {
return timthumb(first_image($id), $width, $height);
}
}
else {
return false;
}
}

// Image from custom field
function custom_image($id) {
return get_post_meta($id, 'image', true);
}

// First image attached to post
function first_image($id) {
global $wpdb;
$first_image = $wpdb->get_results("SELECT guid FROM $wpdb->posts WHERE post_parent = '$id' AND post_type = 'attachment' ORDER BY `post_date` ASC LIMIT 0,1");
if ($first_image) {
return $first_image[0]->guid;
}
}

// Build & resize image
function timthumb($image, $width, $height) {
$image_parsed = parse_url($image);
$url_parsed = parse_url(get_permalink());
// TimThumb can only process images on the same domain as it is
// If the image IS at the same domain
// AND it hasn't been disabled in the admin panel, then process it
// Otherwise, resize with raw HTML
if (get_option('viva_timthumb') != 'on' && $image_parsed['host'] == $url_parsed['host']) {
$path = get_bloginfo('template_directory') . '/viva/post-preview/timthumb.php?src=' . $image . '&amp;w=' . $width . '&amp;h=' . $height . '&amp;zc=1';
}
else {
// Remote image or TimThumb is disabled in Admin Panel
$path = $image;
}
return '<img src="' . $path . '" alt="Post Image" width="' . $width . '" height="' . $height . '" />';
}