无法将通过前端表单上传的文件设置为特色图片

时间:2015-03-17 作者:user3117694

我有一个允许输入姓名、电子邮件和;照片当我点击提交时,我希望它在名为“联系人”的posttype中插入一行,其中包含表单提交的信息和作为特色图像的图像,但it does not set the image as featured image

我的代码

<?php

 if (isset($_POST[\'submit\'])) {    

     $yourname=$_POST[\'yourname\'];
     $email=$_POST[\'email\'];
     $myimage=$_POST[\'myimage\'];    

$my_post = array(
 \'post_title\' => $youname, 
 \'post_status\' => \'publish\',
 \'post_author\' => 1,
 \'post-thumbnails\' => $myimage
);
$post_id = wp_insert_post( $my_post );
if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $imageid = insert_attachment($file,$pid);    
    }
}
set_post_thumbnail($post_id,$imageid);
update_field( "field_5507c9", $email, $post_id );   
}   
?>

<form action="" method="POST">
         Your Name: <input type="text" name="yourname" value=""> <br>
         Your Email:  <input type="text" name="email" value=""> <br>
         Image: <input type="file" name="myimage" id=""><br>    
        <input type="submit" name="submit" value="submit" />           
</form>
将以下内容添加到函数中。php

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 = media_handle_upload( $file_handler, $post_id );

    if ($setthumb) update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
    return $attach_id;
}
另外,是否有任何方法可以检查行是否已上载&;如果插入完成,则回显消息,然后在几秒钟后重定向到新的url。

1 个回复
SO网友:wordpress_developer_me

首先,您需要添加enctype=“多部分/表单数据”以使表单支持文件上载。

到目前为止,您已将图像附加到帖子,但尚未插入它们。试试这样的

<?php 
$args = array( \'post_type\' => \'attachment\', \'numberposts\' => -1, \'post_status\' =>   null, \'post_parent\' => $post->ID );  
$attachments = get_posts($args);  
if ($attachments) { 
    foreach ( $attachments as $attachment ) { ?>

    <?php echo apply_filters( \'the_title\' , $attachment->post_title ); ?>

    <?php the_attachment_link( $attachment->ID , false ); ?>

<?php }  
}
?>

结束