以下是我从kg_video_attachment_fields_to_save()
过滤附件\\u字段\\u以保存的函数:
$thumb_url = $attachment[\'kgflashmediaplayer-poster\'];
//insert the $thumb_url into the media library if it does not already exist
if ( ! ($thumb_id = get_attachment_id_from_src( $thumb_url ) ) ) {
$post_id = $post[\'ID\'];
$desc = $attachment[\'post_title\'] . \' thumbnail\';
//is image in uploads directory?
$upload_dir = wp_upload_dir();
if ( FALSE !== strpos( $url, $upload_dir[\'baseurl\'] ) ) {
$wp_filetype = wp_check_filetype(basename($thumb_url), null );
$filename = preg_replace(\'/\\.[^.]+$/\', \'\', basename($thumb_url));
$attachment = array(
\'guid\' => $thumb_url,
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => $desc,
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$thumb_id = wp_insert_attachment( $attachment, basename($thumb_url), $post_id );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $thumb_id, basename($thumb_url) );
wp_update_attachment_metadata( $thumb_id, $attach_data );
} else { //not in uploads so we\'ll have to sideload it
$tmp = download_url( $thumb_url );
// Set variables for storage
// fix file filename for query strings
preg_match(\'/[^\\?]+\\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/\', $thumb_url, $matches);
$file_array[\'name\'] = basename($matches[0]);
$file_array[\'tmp_name\'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array[\'tmp_name\']);
$file_array[\'tmp_name\'] = \'\';
}
// do the validation and storage stuff
$thumb_id = media_handle_sideload( $file_array, $post_id, $desc );
// If error storing permanently, unlink
if ( is_wp_error($thumb_id) ) {
@unlink($file_array[\'tmp_name\']);
return $thumb_id;
}
if ( $local_src = wp_get_attachment_url( $thumb_id ) ) {
update_post_meta($post[\'ID\'], \'_kgflashmediaplayer-poster\', $local_src);
}
} //end sideload
} //end get_attachment_id_from_src
if(!is_wp_error($thumb_id)) {
$thumb_id = intval( $thumb_id );
update_post_meta($post[\'ID\'], \'_kgflashmediaplayer-poster-id\', $thumb_id);
}
视频的自定义缩略图ID现在存储在元字段中:
_kgflashmediaplayer-poster-id
function get_attachment_id_from_src ($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid=\'$image_src\'";
$id = $wpdb->get_var($query);
return $id;
}
我不喜欢
get_attachment_id_from_src()
但没有内置的方法来实现这一点。我应该添加一个检查,以便如果当前src与旧源相同,则不需要运行此查询。embedder插件为每个视频创建了许多潜在的缩略图,无需将它们全部插入媒体库。。。。因此,每当保存媒体附件时,就会触发此操作,并应涵盖媒体库中已有的图像、媒体目录中但不在库中的图像以及其他服务器上的图像(这些服务器会被侧加载,并且URL会调整为新的本地URL)