有人能给我一个上传图片的代码吗?我尝试了很多,但没有一个有效,这就是我所拥有的:
$post = array(
\'comment_status\' => $comment_status,
\'ping_status\' => \'open\',
\'post_author\' => $user_id,
\'post_content\' => \'\',
\'post_status\' => $status,
\'post_title\' => $title,
\'post_type\' => \'post\',
);
$post_id = wp_insert_post($post);
if($_FILES[\'image_imagepost\'][\'error\'] == 0) {
function insert_attachment($file_handler,$post_id,$setthumb=\'false\'){
// check to make sure its a successful upload
if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
$attach_id = ( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
return $attach_id;
}
我试着发一篇帖子并上传一张图片,帖子还可以,但图片没有上传到媒体上。谢谢
SO网友:I.Alex
我看了又看,终于找到了适合我的工作。
$upload = wp_upload_bits( $_FILES[\'image\'][\'name\'], null, file_get_contents( $_FILES[\'image\'][\'tmp_name\'] ) );
$wp_filetype = wp_check_filetype( basename( $upload[\'file\'] ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
\'guid\' => $wp_upload_dir[\'baseurl\'] . _wp_relative_upload_path( $upload[\'file\'] ),
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename( $upload[\'file\'] )),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $upload[\'file\'], $post_id );
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload[\'file\'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta( $post_id, \'_thumbnail_id\', $attach_id );
wp_redirect( site_url() . \'/thank-you/\' );
die();
}
发件人
here