我试图将图片插入自定义帖子类型。在使用wp_generate_attachment_metadata
后,我已阅读以使用media_handle_upload
。
$pid = wp_insert_post($new_post);
$attachment_id = media_handle_upload( 'art_upload[$i]', $pid );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $file);
wp_update_attachment_metadata( $attachment_id, $attach_data );
如何获取变量$file
?
答案 0 :(得分:0)
我使用此代码在数据库中插入图像
<?php
$post = array(
'post_content' => $method, // The full text of the post.
'post_name' => $recipetitle, // The name (slug) for your post
'post_title' => $recipetitle, // The title of your post.
'post_status' => 'publish', // Default 'draft'.
'post_type' => 'recipespost', // Default 'post'.
'post_author' => 1, // The user ID number of the author. Default is the current user ID.
'menu_order' => '0', // If new post is a page, sets the order in which it should appear in supported menus. Default 0.
'post_password' => '', // Password for post, if any. Default empty string.
'post_excerpt' => '', // For all your post excerpt needs.
'comment_status' => 'open' , // Default is the option 'default_comment_status', or 'closed'.
'post_category' => $recipetype, // Default empty.
);
$post_id = wp_insert_post( $post);
wp_set_post_categories( $post_id);
add_post_meta($post_id, 'diet', $dyettype, true);
$filename = $_FILES["recipeimage"]["name"];
$uploads = wp_upload_dir();
//file_put_contents($file, $image_data);
$file_array = array(
'name' => $_FILES['recipeimage']['name'],
'type' => $_FILES['recipeimage']['type'],
'tmp_name' => $_FILES['recipeimage']['tmp_name'],
'error' => $_FILES['recipeimage']['error'],
'size' => $_FILES['recipeimage']['size'],
);
// required for wp_handle_upload() to upload the file
$upload_overrides = array( 'test_form' => FALSE );
if ( !empty( $file_array['name'] ) ) {
// upload the file to the server
$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );
// checks the file type and stores in in a variable
$wp_filetype = wp_check_filetype( basename( $uploaded_file['recipeimage'] ), null );
// set up the array of arguments for "wp_insert_post();"
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/.[^.]+$/', '', basename( $uploaded_file['recipeimage'] ) ),
'post_content' => '',
'post_author' => $logged_in_user,
'post_status' => 'inherit',
'post_type' => 'attachment',
'guid' => $uploads['url'] . '/' . $file_array['name']
);
// insert the attachment post type and get the ID
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_file['recipeimage'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
// update the attachment metadata
wp_update_attachment_metadata( $attach_id, $attach_data );
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
set_post_thumbnail( $post_id, $post_thumbnail_id );
}
?>