Created
March 18, 2018 06:02
-
-
Save jackmcpickle/d3e4d0626df5896e70595fdfed8fa93c to your computer and use it in GitHub Desktop.
attach media that was uploaded in post as thumbnails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This grabs to parent post of the attachment, which is the post it was uploaded into and makes it a thumbnail of the post.