【问题标题】:wordpress attachment error in custom post form自定义帖子表单中的wordpress附件错误
【发布时间】:2016-07-29 06:34:07
【问题描述】:

我有一个用于编辑自定义帖子的自定义表单,此表单供前端用户编辑他们的帖子和相应的附件。对于附件部分,我有两个输入文件元素,格式为可以上传图像和视频,我在下面的 PHP 代码中捕获了上传的附件。

            if ($_FILES) {

        foreach ($_FILES as $file => $array) {

            if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK || $_FILES[$file]['error'] === UPLOAD_ERR_NO_FILE) {
                $ermg = "upload error : " . $_FILES[$file]['error'];
                continue;
            } else {
                $attach_id = media_handle_upload($file, $post_id);
                $type = get_post_mime_type($attach_id);
                if ($type === 'image/jpeg' || $type === 'image/png') {
                    update_post_meta($new_post, '_thumbnail_id', $attach_id);
                } elseif ($type === 'video/mp4' || $type === 'video/quickime') {
                    update_post_meta($new_post, '_video_id', $attach_id);
                }
            }
            return $ermg;
        }
    }

这里的问题是,如果同时上传两个附件,我的代码不会只捕获一个附件,而上传单个附件可以正常工作。

除此之外,还有一个问题,每次上传时,我都会在媒体库中看到一个没有标题的新未知附件,下面是屏幕截图,预计不会出现这个新的未知附件。有人可以帮忙吗?

【问题讨论】:

  • 通过将if ($_FILES[$file]['error'] 之后的运算符从!== 更改为!= 我可以同时上传这两个文件,但仍然会创建未知文件:(

标签: php wordpress forms


【解决方案1】:

试试这个:(在function.php中)

require_once(ABSPATH.'wp-admin/includes/admin.php');
if ($_FILES) 
{
    foreach ($_FILES as $file => $array) 
    {    
        $file_return = wp_handle_upload( $file, array('test_form' => false ) );
        if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) 
        {
            $ermg = "upload error : " . $_FILES[$file]['error'];
            continue;
        } 
        else 
        {
            $filename=$file_return['file'];
            $type=$file_return['type'];
            $attachment=array(
                'post_mime_type' => $file_return['type'],
                'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
                'post_content' => '',
                'post_status' => 'inherit',
                'guid' => $file_return['url']
            );
            $attachment_id=wp_insert_attachment($attachment, $file_return['url']);
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data=wp_generate_attachment_metadata( $attachment_id, $filename );
            wp_update_attachment_metadata($attachment_id,$attachment_data);
            if ($type === 'image/jpeg' || $type === 'image/png') {
                update_post_meta($new_post, '_thumbnail_id', $attachment_id);
            } elseif ($type === 'video/mp4' || $type === 'video/quickime') {
                update_post_meta($new_post, '_video_id', $attachment_id);
            }   
        }
        return $ermg;
    }
}

【讨论】:

  • 我试过你的代码,但它不起作用,未知的附件仍在创建中。
猜你喜欢
  • 2014-01-23
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多