使用wp_remote_get()函数

时间:2015-07-12 13:05:22

标签: php wordpress image

我正在使用wp_remote_get从网址获取图片并将其作为精选图片附加到帖子中。我最初使用来自this帖子的一些帮助来完成它,并且图像已成功设置为特色图像并在后端显示但现在图像已成功设置为特色图像但仅显示图像名称(如同图像文件的路径被破坏了。
当我使用ftp进入图像路径时,我可以看到图像文件,但是当我尝试打开图像时,它表示不支持的格式。
下面是我用来获取图像的代码

$upload_dir = wp_upload_dir();            
$image_url = $one_post->images[0];
$image_data = wp_remote_get($image_url);
//Get image and set unique file name
$filename = $new_post_id."_".$one_post->ID."_".basename($image_url);    
if (wp_mkdir_p($upload_dir['path'])) {
     $file = $upload_dir['path'] . '/' . $filename;
     } else {
       $file = $upload_dir['basedir'] . '/' . $filename;
     }
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
           'post_mime_type' => $wp_filetype['type'],
           'post_title' => sanitize_file_name($filename),
           'post_content' => '',
           'post_status' => 'inherit',
      );            
$attach_id = wp_insert_attachment($attachment, $file, $new_post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($new_post_id, $attach_id);

如果我用文本编辑器打开图像文件,我会看到类似下面的内容

ArrayÿØÿà JFIF

编码时是否有错误?
请纠正我的错误。

1 个答案:

答案 0 :(得分:3)

正如我在评论中提到的,由于您使用wp_remote_get()file_put_contents()的方式,您已经看到了这个问题。

我也看到你重复了一些WordPress功能。在下面的示例中,我重写了您的代码以利用现有的WordPress功能。

$image_url = $one_post->images[0];

$tmp = download_url( $image_url );

// fix filename for query strings
preg_match( '/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $image_url, $matches );

$file_array = array(
    'name'     => $new_post_id . '_' . $one_post->ID . '_' . basename( $matches[0] ),
    'tmp_name' => $tmp
);

// Check for download errors
if ( is_wp_error( $tmp ) ) {
    @unlink( $file_array['tmp_name'] );
    return false;
}

$id = media_handle_sideload( $file_array, $new_post_id );

// Check for handle sideload errors.
if ( is_wp_error( $id ) ) {
    @unlink( $file_array['tmp_name'] );
    return false;
}

// Set post thumbnail.
set_post_thumbnail( $new_post_id, $id );

基于media_handle_sideload()https://codex.wordpress.org/Function_Reference/media_handle_sideload

的法典页面上给出的示例