Last active
December 21, 2015 13:18
-
-
Save brichards/6311526 to your computer and use it in GitHub Desktop.
This file contains 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 | |
class HHW_WP_CLI_Commands extends WP_CLI_Command { | |
/** | |
* Update post meta for all posts that have sdac_post_thumbnail key. | |
* Move associated meta value to featured image. | |
*/ | |
function fix_images() { | |
global $wpdb; | |
// Grab all of the posts with a meta key of sdac_post_thumbnail | |
$posts = $wpdb->get_results( | |
" | |
SELECT meta.post_id as ID, | |
attachment.ID as thumbnail_id | |
FROM $wpdb->postmeta as meta | |
INNER JOIN $wpdb->posts as attachment | |
ON attachment.guid = meta.meta_value | |
AND attachment.post_type = 'attachment' | |
WHERE meta.meta_key = 'sdac_post_thumbnail' | |
AND meta.meta_value LIKE 'http://hiphopwired.com%' | |
GROUP BY meta.post_id | |
" | |
); | |
// If we have no posts, we're done | |
if ( empty( $posts ) ) { | |
WP_CLI::success( 'Script Complete: no more posts to update.' ); | |
return; | |
// Otherwise, iterate through and update their meta | |
} else { | |
// Setup our counters | |
$count = 0; | |
$counter = count( $posts ); | |
// Report how many posts we found | |
WP_CLI::success( 'Found ' . $counter . ' posts' ); | |
//Loop through all posts found above. | |
foreach( $posts as $post ) { | |
if ( empty( $post->thumbnail_id ) ) { | |
WP_CLI::warning( 'No post matching' ); | |
} else { | |
if ( $updated = update_post_meta( $post->ID, '_thumbnail_id', $post->thumbnail_id ) ) { | |
$count++; | |
WP_CLI::success( sprintf( | |
'%1$d of %2$d: %3$s updated successfully', | |
$count, | |
$counter, | |
get_the_title( $post->ID ) | |
) ); | |
} | |
} | |
} | |
// Report back on how we did | |
if ( $count >= $counter ) | |
WP_CLI::success( 'All posts have been updated.' ); | |
elseif ( $count ) | |
WP_CLI::success( $count . ' of ' . $counter . ' posts have been updated.' ); | |
else | |
WP_CLI::success( 'No posts have been updated.' ); | |
} | |
} | |
} | |
WP_CLI::add_command( 'hhw_fix_images', 'HHW_WP_CLI_Commands' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment