【发布时间】:2016-06-07 02:11:33
【问题描述】:
我正在使用 wordpress 中的前端表单来创建自定义帖子类型并上传附加到该帖子的图片。
以下是我目前的代码。帖子已创建,但问题是图像未上传到附加到该帖子的服务器。另一方面,我希望在发送表单之前对图像进行预可视化,就像 wordpress 用于管理区域一样。
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['new_cpt_action'] ) && $_POST['new_cpt_action'] == "new_cpt" && isset( $_POST['new_cpt-form'] ) && wp_verify_nonce( $_POST['new_cpt-form'], 'create_new_cpt' ) ){
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['s_name'])) {
$s_name = $_POST['s_name'];
} else {
$error = 'Please insert a name';
}
if (empty($error)) {
$new_post = array(
'post_title' => $s_name,
'post_status' => 'pending',
'post_type' => 'my_cpt',
);
//Save the post
$post_id = wp_insert_post($new_post);
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = wp_insert_attachment($file, $post_id);
}
}
}
//Redirect to the new post
if ( $post_id ) {
wp_redirect(home_url('site/'.$post_id));
exit;
}
}
}
}
还有形式:
<form id="new_post" name="new_post" method="post" action="" class="" enctype="multipart/form-data">
<input type="text" id="s_name" name="s_name"/>
<input type="file" name="s_image" id="s_image" tabindex="25" />
<input type="submit" value="Create post and upload image" id="submit" name="submit"/>
<input type="hidden" id="new_cpt_action" name="new_cpt_action" value="new_cpt" />
</form>
如果你能告诉我我缺少什么,那就太好了。 谢谢
【问题讨论】:
标签: wordpress image file-upload frontend custom-post-type