Skip to content

Instantly share code, notes, and snippets.

@jackmcpickle
Created March 18, 2018 06:02
Show Gist options
  • Save jackmcpickle/d3e4d0626df5896e70595fdfed8fa93c to your computer and use it in GitHub Desktop.
Save jackmcpickle/d3e4d0626df5896e70595fdfed8fa93c to your computer and use it in GitHub Desktop.
attach media that was uploaded in post as thumbnails
<?php
add_action('init', 'update_business_thumbnails');
function update_business_thumbnails()
{
if (!isset($_GET['update_thumbnails'])) return ;
$args = [
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => ['all'],
'fields' => 'ids'
];
$mediaIds = (new WP_Query($args))->posts;
foreach ($mediaIds as $fileId) {
print_r($fileId. '\n');
$postId = wp_get_post_parent_id( $fileId );
if (!$postId) {
return;
}
if (has_post_thumbnail($postId)) {
return;
}
$updated = update_post_meta( $postId, '_thumbnail_id', $fileId );
if ( $updated ) {
wp_cache_set( 'last_changed', microtime(), 'posts' );
dump('updated\n');
} else {
dump('couldnt update'. (get_post($postId))->post_title . '\n');
}
}
die('Done');
}
@jackmcpickle
Copy link
Author

This grabs to parent post of the attachment, which is the post it was uploaded into and makes it a thumbnail of the post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment