Wordpress和AJAX - 上传图片为特色

时间:2021-11-28 06:59:13

I'm using wordpress with ajax in a frontend form and I'd need support for handling and uploading the featured image. My problem is specifically about the featured image. My html is something like:

我在前端形式中使用带有ajax的wordpress,我需要支持处理和上传特色图像。我的问题是关于特色图像。我的HTML是这样的:

<form id="msform" action="#" method="post" enctype="multipart/form-data">
//inputs of various nature
<input type="file" name="main_image" id="main_image"  multiple="false" value="" accept=".png, .jpg, .jpeg, .gif"/>
<input type="submit" class="submit" value="Publish"/>
</form>

I send data to a php function (following Wordpress methods) through this jquery:

我通过这个jquery将数据发送到php函数(遵循Wordpress方法):

function apfaddpost() {
    var formData = $('#msform').serialize();
    formData.append('main_image', $('#main_image')[0].files[0]); //here should be the problem
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: formData + '&action=apf_addpost', //here I send data to the php function calling the specific action
        processData: false,
        contentType: false

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

My function php is something like

我的函数php就像

function apf_addpost() {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    $file_handler = 'main_image';
    $attach_id = media_handle_upload($file_handler,$pid );
    update_post_meta($pid,'_thumbnail_id',$attach_id);
}

Important to say: all the other data like title, description, tags are correctly serialized and sent. The problem is for the image. I've tried also to use the $_FILES[] handler without success and I suppose that my ajax code is not so great then. Can you help me? If you have any other workaround for this issue please share! Thanks in advance.

重要的是:标题,描述,标签等所有其他数据都已正确序列化并发送。问题出在图像上。我也试过使用$ _FILES []处理程序但没有成功,我想我的ajax代码不是那么好。你可以帮我吗?如果您对此问题有任何其他解决方法,请分享!提前致谢。

[SOLVED] EDIT

[求助]编辑

Thanks to the answers below I've just changed my ajax into

感谢下面的答案,我刚刚把我的ajax改成了

function apfaddpost() {
    var fd = new FormData($('#msform')[0]);
    fd.append( "main_image", $('#main_image')[0].files[0]);
    fd.append( "action", 'apf_addpost');      
   //Append here your necessary data
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: fd, 
        processData: false,
        contentType: false,

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

I've discovered that FormData() allows to serialize files, thing that .serialize() method doesn't. Known that, it has been simple to move on. Thanks.

我发现FormData()允许序列化文件,而.serialize()方法则没有。众所周知,继续前进很简单。谢谢。

1 个解决方案

#1


4  

Please Try :

请尝试 :

I have modify your code.

我修改了你的代码。

Jquery (added FormData() and append)

Jquery(添加了FormData()并追加)

function apfaddpost() {
    var fd = new FormData();
    fd.append( "main_image", $('#main_image')[0].files[0]);
    fd.append( "action", 'apf_addpost');      
   //Append here your necessary data
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: fd, 
        processData: false,
        contentType: false

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

in function.php

在function.php中

I have added file upload code

我添加了文件上传代码

/******FILE UPLOAD*****************/
function upload_user_file( $file = array() ) {    
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );
    $file_return = wp_handle_upload( $file, array('test_form' => false ) );
    if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
        return false;
    } else {
        $filename = $file_return['file'];
        $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( 0 < intval( $attachment_id ) ) {
          return $attachment_id;
        }
    }
    return false;
}

now modify your function apf_addpost() in function.php

现在修改function.php中的函数apf_addpost()

function apf_addpost() {
     foreach( $_FILES as $file ) 
     {  
          if( is_array( $file ) ) {
                $attach_id =upload_user_file();  //Call function 
                update_post_meta($pid,'_thumbnail_id',$attach_id);
          }
     }

}

#1


4  

Please Try :

请尝试 :

I have modify your code.

我修改了你的代码。

Jquery (added FormData() and append)

Jquery(添加了FormData()并追加)

function apfaddpost() {
    var fd = new FormData();
    fd.append( "main_image", $('#main_image')[0].files[0]);
    fd.append( "action", 'apf_addpost');      
   //Append here your necessary data
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: fd, 
        processData: false,
        contentType: false

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

in function.php

在function.php中

I have added file upload code

我添加了文件上传代码

/******FILE UPLOAD*****************/
function upload_user_file( $file = array() ) {    
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );
    $file_return = wp_handle_upload( $file, array('test_form' => false ) );
    if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
        return false;
    } else {
        $filename = $file_return['file'];
        $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( 0 < intval( $attachment_id ) ) {
          return $attachment_id;
        }
    }
    return false;
}

now modify your function apf_addpost() in function.php

现在修改function.php中的函数apf_addpost()

function apf_addpost() {
     foreach( $_FILES as $file ) 
     {  
          if( is_array( $file ) ) {
                $attach_id =upload_user_file();  //Call function 
                update_post_meta($pid,'_thumbnail_id',$attach_id);
          }
     }

}