Skip to content

Instantly share code, notes, and snippets.

@ozrabal
Last active July 25, 2022 20:33
Show Gist options
  • Save ozrabal/429d65e68caeccd83eddc8b83a1a1d0f to your computer and use it in GitHub Desktop.
Save ozrabal/429d65e68caeccd83eddc8b83a1a1d0f to your computer and use it in GitHub Desktop.
Convert yapb (Yet Another PhotoBlog Wordpress Plugin which is not anymore maintained) images to native Wordpress post feature image
<?php
function convert_yapb_images_to_post_thumbnail () {
require_once ABSPATH . 'wp-admin/includes/image.php';
global $wpdb;
$imagefileList = array();
$imageRows = $wpdb->get_results(
'SELECT id,post_id,uri FROM ' . YAPB_TABLE_NAME . ' WHERE processed<>1 ORDER BY id'
);
//$len=count($imageRows)
$len = 100;
for ($i=0; $i<$len; $i++) {
$row = $imageRows[$i];
$yapbImage = new YapbImage($row->id, $row->post_id, $row->uri);
array_push($imagefileList, [$row->post_id, $yapbImage->systemFilePath()]);
$post = get_post($row->post_id);
$file_path = $yapbImage->systemFilePath();
$file_name = basename($file_path);
$file_type = wp_check_filetype($file_name, null);
$attachment_title = sanitize_file_name(pathinfo($file_name, PATHINFO_FILENAME));
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($post_info, $file_path, $post->ID);
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($post->ID, $attach_id);
$q = $wpdb->prepare(
'UPDATE ' . YAPB_TABLE_NAME . ' SET processed=1 WHERE id=%s',
$row->id
);
$wpdb->query($q);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment