Skip to content

Instantly share code, notes, and snippets.

@bigdawggi
Created November 12, 2012 23:53
Show Gist options
  • Save bigdawggi/4062892 to your computer and use it in GitHub Desktop.
Save bigdawggi/4062892 to your computer and use it in GitHub Desktop.
Import featured image on demand
add_filter(
'get_post_metadata',
array($this, 'maybe_grab_simpleview_photo_for_featured_image'),
10,
4
);
/**
* On the request for a post's featured image, it goes and retrieves it from the 3rd party site,
* attaches it to the current post, then sets it as a featured image. This only happens once per post.
*/
public function maybe_grab_simpleview_photo_for_featured_image($value, $object_id, $meta_key, $single) {
// someone's checking for featured image presence
if ($meta_key == '_thumbnail_id') {
$post = get_post($object_id);
if ($post
&& $post->post_type == 'listing'
&& !get_post_meta($object_id, '_cf_imported_thumbnail', true) // haven't already imported
&& !get_post_meta($object_id, '_cf_attempted_thumb_import', true) // AND haven't already attempted to import
) {
$post_id = $object_id;
$listing = new CF_SimpleView_Listing($post_id);
$url = $listing->get_photo_url();
if ($url) {
if (!function_exists('media_sideload_image')) {
require_once ABSPATH.'wp-admin/includes/media.php';
require_once ABSPATH.'wp-admin/includes/file.php';
require_once ABSPATH.'wp-admin/includes/image.php';
}
// retrieve the remote image, and attach to our post
$img_html = media_sideload_image($url, $post_id);
if ($img_html && !is_wp_error($img_html)) {
// Now make it the featured image for the post
$images = get_children(array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image'
));
if ($images) {
$first_image = array_shift($images);
update_post_meta($post_id, '_thumbnail_id', $first_image->ID);
update_post_meta($post_id, '_cf_imported_thumbnail', true);
}
}
else {
// couldn't grab the image from SimpleView...don't keep trying
update_post_meta($post_id, '_cf_attempted_thumb_import', true);
}
}
}
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment