I'm creating an image upload form for a custom post type but i don't know how to upload the image to the custom post type. The custom post type is called 'art'.
Here is my code.
form html
<form id="art_submission_form" enctype="multipart/form-data" method="post" action="art_process.php">
<div class="art_upload_container" <?php echo $style; ?>>
<div class="art_sub_row">
<select class="art_sub_select" name="art_creation_date">
<option value="Creation Date">Creation Date</option>
<?
$dates = array("2014","2013","2012","2011","2010","2009","2008","2007","2006","2005","2004","2003","2002","2001","2000","1999",
"1998","1997","1996","1995","1994","1993","1992","1991","1990","1989","1988","1987");
foreach($dates as $value) {
echo "<option value='$value'>$value</option>";
}
?>
</select>
<div class="art_sub_col"><label>Art Title</label><input type="text" class="art_title" name="art_title[]" value="<?php echo $art_title; ?>" /></div>
</div>
<div class="art_sub_row">
<div class="art_sub_col"><label>Width(cm)</label><input type="text" class="art_width" name="art_width[]" value="<?php echo $art_width; ?>" /></div>
<div class="art_sub_col"><label>Height(cm)</label><input type="text" class="art_height" name="art_height[]" value="<?php echo $art_height; ?>" /></div>
<div class="art_sub_col"><label>Price</label><input type="text" class="art_price" name="art_price[]" value="<?php echo $art_price; ?>" /></div>
</div>
<div class="art_sub_row">
<div class="art_sub_col"><label>Upload Art:</label> <input type="file" name="art_upload[]" class="art_upload"></div>
</div>
</div>
<input type="submit" class="art_sub_send" value="Send" />
</form>
art_process.php - what i've done so far
$art_title = $_POST['art_title'];
$i = 0;
foreach($art_title as $value) {
$art_title = $_POST['art_title'][$i];
$art_width = $_POST['art_width'][$i];
$art_height = $_POST['art_height'][$i];
$art_price = $_POST['art_price'][$i];
$art_creation_date = $_POST['art_creation_date'][$i];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $art_title,
'post_status' => 'draft',
'post_type' => 'art'
);
//save the new post
$pid = wp_insert_post($new_post);
$i++;
}
Is there a built in wordpress function to upload image to a custom post type?
media_handle_upload()
is the function you're looking for:
handles the file upload POST request, and creates the attachment post in the database.
If successful, you can use the parent post ID ($pid
) and the attachment ID to set the image as post thumbnail with set_post_thumbnail()
.