Es un caso común para migraciones en wordpress. Necesitamos que imágenes que están en una URL externa, quizá otro wordpress, se importen a la carpeta 'uploads' y que se genere correctamente un attachment de wordpress con sus metadatos, de manera que sea navegable desde la media gallery y se pueda asociar a un post. A esto le podemos añadir el comprobar que la imagen no exista ya para evitar trabajo redundante e innecesario.
#!java
/**
* Helper function to set the post title of an attachment
*
* @param String $filename Name of the file, for instance 'Attachment Example.jpg'
*
* @return String A valid post title for the attachment related to that filename, for instance 'attachment-example'
*/
function attachment_post_title($filename)
{
return sanitize_title(
substr(
$filename,
0,
strrpos($filename, ".")
)
);
}
/**
* Helper function to download an image to uploads folder from a remote URL
*
* @param String $url Absolute URL of remote asset
* @param String $date Date of the attachment in the WP default format 'yyyy-mm-dd hh:mm:ss'
* @param Integer $parent_id (optional) Id of the parent post
*
* @return Integer $attach_id Id of the newly created attachment
*/
function insert_attachment_from($url, $date, $author=null, $parent_id=null)
{
// Get URL and check the content type
$get = wp_remote_get($url);
$type = wp_remote_retrieve_header($get, 'content-type');
if(!$type) return false;
// Get filename and post title
$filename = basename($url);
$title = attachment_post_title($filename);
// Check if file exists already
if( post_exists($title, null, null, 'attachment') )
{
WP_CLI::log("File '" . $filename . "' exists already");
$attach_id = get_page_by_title(
$title,
'OBJECT',
'attachment'
)->ID;
} else {
WP_CLI::log("Creating file '".$filename."' of type '".$type."'");
// Create file in '/wp-content/uploads/YYYY/MM'
$mirror = wp_upload_bits(
$filename, '',
wp_remote_retrieve_body($get),
date('Y/m', strtotime($date))
);
// Create post of 'attachment' post type, linked to the media file
$attachment_args = [
'post_title' => $title,
'post_mime_type' => $type,
'post_date' => $date,
'post_content' => '',
'post_status' => 'inherit'
];
if($author)
$attachment_args['post_author'] = $author;
if($parent_id)
$attachment_args['post_parent'] = $parent_id;
$attach_id = wp_insert_attachment(
$attachment_args,
$mirror['file']
);
// Set attachment metadata to be displayed in WP media gallery
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata(
$attach_id,
$mirror['file']
);
wp_update_attachment_metadata(
$attach_id,
$attach_data
);
}
return $attach_id;
}