图像上传图像URL或图像链接在WordPress中

时间:2017-05-10 05:41:58

标签: wordpress upload media

如何通过图像URL上传图像或通过编程在WordPress媒体库中链接图像。

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式传递$_REQUEST['image']通过网址来完成此操作。

// $filename should be the path to a file in the upload directory.
$filename = $_REQUEST['image'];

// The ID of the post this attachment is for.
$parent_post_id = 37;

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), 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( $filename ), 
    'post_mime_type' => $filetype['type'],
    'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $parent_post_id, $attach_id );

只需跳过您不需要的部分,例如将图片设置为发布 - > set_post_thumbnail(),我添加了它以便更好地参考将图像附加到帖子。

相关问题