Wordpress and AJAX - Upload image as featured

前端 未结 1 1913
太阳男子
太阳男子 2021-02-09 07:41

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 ht

相关标签:
1条回答
  • 2021-02-09 07:59

    Please Try :

    I have modify your code.

    Jquery (added FormData() and append)

    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

    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 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);
              }
         }
    
    }
    
    0 讨论(0)
提交回复
热议问题