Skip to content

Instantly share code, notes, and snippets.

Created September 4, 2015 20:06
Show Gist options
  • Save anonymous/5bbde7ee2cddad8e66a6 to your computer and use it in GitHub Desktop.
Save anonymous/5bbde7ee2cddad8e66a6 to your computer and use it in GitHub Desktop.
<?php
require_once dirname( __FILE__ ) . '/wp-load.php';
//$existing_image = 'http://guidevoyage.org.dev' . '/wp-content/uploads/2010/12/122010_0314_LamdinadeSo1.png';
//Locate the attachment post's ID in the database based on the GUID.
function getIDfromGUID( $full_image_url ){
global $wpdb;
return $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE `post_type` = 'attachment' AND `guid` = %s ", $existing_image ) );
//SELECT ID FROM `wp_posts` WHERE `guid` = 'http://guidevoyage.org.dev/wp-content/uploads/2010/12/122010_0314_LamdinadeSo1.png' AND `post_type` = 'attachment'
}
// // Run a loop for all posts that are articles
$posts = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => -1 ) );
// Check that the query is not empty
if ( $posts->have_posts() ): while ( $posts->have_posts() ): $posts->the_post();
//Loop through each individual post and work some magic
foreach ( $posts as $post) {
//Check that the post has an associated post_meta custom field for "Image" that's not empty, AND that the thumbnail is not set.
$existing_image = get_post_meta($post->ID, 'Image');
var_dump( $post );
echo ( 'Working on ' . $post->ID . 'The partial URL is: ' . $existing_image );
die();
$full_image_url = 'http://guidevoyage.org.dev/' . $existing_image;
if ( ( ! empty( $existing_image ) && ! has_post_thumbnail( $post->ID ) ) ) {
$thumbnail_id = getIDfromGUID( $existing_image );
if ( ! empty( $thumbnail_id ) ) {
//Set the the Featured image we found to the matching Attachment Post from the URL
//set_post_thumbnail( $post->ID, $thumbnail_id );
//Keep things tidy by removing the Image custom field content
//delete_post_meta( $post->ID, 'Image' );
echo ( 'Post # ' . $post->ID . ' : ALL GOOD!!' . "\r\n");
}
else {
echo ( 'Post # ' . $post->ID . ' : The ATTACHMENT post is missing' . "\r\n");
}
}
else {
if ( empty( $existing_image ) ) {
echo ( 'Post # ' . $post->ID . ' : has no CUSTOM field image set.' . "\r\n" );
}
else if ( has_post_thumbnail( $post->ID ) ) {
echo ( 'Post # ' . $post->ID . ' : has a THUMBNAIL already.' . "\r\n" );
}
}
}
endwhile; endif;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment