给你:
// Returns the attachment ID uploaded
$attach_id = omakUploadImage( $file, $post_id );
// Set an image as Featured Image to post with $post_id
// This is the cream you needed, Nivos
set_post_thumbnail( $post_id, $attach_id );
// omakUploadImage is a custom function which takes an input type="file" value
function omakUploadImage( $file, $post_id=\'\' ) {
if( $post_id == \'\' ) {
global $post;
$post_id = $post->ID;
}
// Get Upload Directory
$uploaddir = wp_upload_dir();
/* echo \'<br/><br/>\';print_r($_FILES); echo \'<br/><br/>\';print_r($file); */
// Create File Name
$uploadfile = $uploaddir[\'path\'] . \'/\' . basename( $file[\'name\'] );
// Create Upload Path, Not Required though
$uploadpath = $uploaddir[\'path\'] . \'/\';
/*
echo \'<br/><br/>\';echo \'upload file: \';print_r($uploadfile);
echo \'<br/><br/>\';echo \'upload path: \';print_r($uploadpath);
*/
// Move Temp Named File to Actual File Name in UploadDir
$moved = move_uploaded_file( $file[\'tmp_name\'] , $uploadfile );
// Get The Image Name
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', $filename),
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
//\'menu_order\' => $_i + 1000
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile, $post_id );
//echo \'<script>alert("AttachId: \'.print_r($attach_id).\'")</script>\';
return $attach_id;
}
希望有帮助!有一些测试代码被注释掉了。
这里是我使用它实现前端发布的地方。http://www.omaksolutions.com/clients/neetinpuri/localmag/submit-your-business