上传的图片无法使用WordPress正确显示

时间:2016-11-11 作者:Preethi

我需要在wordpress中以编程方式插入帖子。。我已完成插入标题和内容。。但图像未上载和附加。。你能给我提个建议吗。。

$post_id = wp_insert_post(
      array(
        \'post_author\'   => $user->ID,
            \'post_title\'    => $Title,
            \'post_content\'   =>$Content,
            \'post_status\'   => \'publish\',
            \'post_type\'   => \'post\',
            \'guid\'      =>      $site_url . \'/?p=\' . $post_id
      )
    );


$Featured_image = http://ecx.images-amazon.com/images/I/51l-rEon-NL._SL110_.jpg;
$year = date("Y");   
$month = date("m"); 
$url = \'/wp-content/uploads/\'. $year . \'/\' . $month . \'/\'  . basename($Featured_image);

// Check the type of file. We\'ll use this as the \'post_mime_type\'.
$filetype = wp_check_filetype( basename( $Featured_image ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
\'guid\'           => $wp_upload_dir[\'url\'] . \'/\' . basename( $Featured_image ), 
\'post_mime_type\' => $filetype[\'type\'],
\'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $Featured_image )),
\'post_content\'   => \'\',
\'post_status\'    => \'inherit\',
\'post_type\' => \'attachment\'
);

// Insert the attachment.

$attach_id = wp_insert_attachment( $attachment,  $year . \'/\' . $month . \'/\'  . basename($Featured_image) ,  $post_id );

require_once( ABSPATH . \'wp-admin/includes/image.php\' );

$attach_data = wp_generate_attachment_metadata( $attach_id, $url );

wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $post_id, $attach_id );
我试过了,但图像显示在这样的媒体上,

enter image description here

同时,图像未存储在uploads文件夹中。。我不知道如何解决这个问题。。有人能推荐我吗。。

1 个回复
最合适的回答,由SO网友:Ranuka 整理而成

有一个函数称为media_sideload_image($file, $post_id, $desc, $return); 从指定的URL下载图像并将其附加到帖子。你可以使用它。

它询问了以下参数。

$文件:(字符串)(必需)要下载的图像的URL

  • $post\\u id:(int)(必需)媒体要关联的post id
  • $desc:(字符串)(可选)图像描述。默认值:null返回:(字符串)(可选)接受“html”(图像标记html)或“src”(URL)。默认值:“html”
  • 成功时返回填充的html img标记,否则返回WP\\u Error对象。

    相关推荐

    Column Images Showing Gaps

    我正在使用带有Avada主题的Wordpress。在页面顶部,我有一个fusion滑块。下面我将设置一个包含2列的容器。我为每一列插入了一幅图像。我无法解决如何消除图像左右两侧的间隙(我需要它们转到屏幕边缘)以及融合滑块与下方两幅图像之间的间隙。谢谢