次のコードを使用して、ページの最初の画像を特集画像としてアップロードしています。
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
function save_first_image(){
global $post, $posts;
$first_image = catch_that_image();
$post_id = $post -> post_id;
$args = array('timeout' => '1200');
$get = wp_remote_get( $first_image,$args );
$type = wp_remote_retrieve_header( $get, 'content-type' );
$mirror = wp_upload_bits(rawurldecode(basename( $first_image )), '', wp_remote_retrieve_body( $get ) );
//Attachment options
$attachment = array(
'post_title'=> basename( $first_image ),
'post_mime_type' => $type
);
// Add the image to your media library and set as featured image
$attach_id = wp_insert_attachment( $attachment, $mirror['file'], $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $first_image );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}
正常に動作していましたが、今では常に壊れた画像を添付しているようです。
誰かがこれを経験したことがありますか - 問題の原因が cloudflare であるかどうか疑問に思っています - しかし、それを無効にしても、まだ壊れた画像がアップロードされています.
すべての画像はサイトの webroot のフォルダーに保存されています。wp_remote_get を使用せずにアップロードする方法はありますか?
ありがとう