使用AJAX和ACF在WordPress注册时将文件上传到用户



因此,我正在尝试创建一个自定义注册表单,用户还可以使用Ajax和Modal上传文件(即简历(。

我找到了这个教程,可以让我这样做,但是问题是,我不确定如何上传也将连接到ACF的文件。

http://felledtuts.com/wordpress/wordpress-ajax-login-and-register-without-a-plugin/

我能够在讨论的帮助下做到这一点,但是只有当我不使用ajax:https://wordpress.stackexchange.com/questions/282586/acf-upload-image-image-in-front-end-with-with-with-custom-form/283079#283079

有人可以帮我吗?谢谢!

注意:我删除了一些可能与我的问题无关的东西,所以请问我是否缺少任何东西。这是我的代码:

<form id="student_register" class="ajax-auth"  action="register" method="post" enctype='multipart/form-data'>
    <p class="status"></p>
    <?php wp_nonce_field('stud-ajax-register-nonce', 'stud_signonsecurity'); ?>
        <label for="stud_email">School Email*</label>
        <input id="stud_email" type="text" class="required email" name="stud_email" placeholder="Enter school email address">
        <label for="stud_signonpassword">Password*</label>
        <input id="stud_signonpassword" type="password" class="required" name="stud_signonpassword">
        <label for="uploadResume" class="custom-file-upload">Upload Your Resume
        </label>
        <input type="file" id="uploadResume" class="uploadResume" name="uploadResume" accept=".doc, .docx,.pdf" style="display:none;" value="">
    </div>
    <input class="submit_button green-btn green-btn--fullWidth" type="submit" value="Submit Registration">
</form>

我的jQuery文件称为ajax-auth-script.js

 //jQuery
    // Perform AJAX login/register on form submit
    $('form#student_register').on('submit', function (e) {
        if (!$(this).valid()) return false;
        $('p.status', this).show().text(ajax_auth_object.loadingmessage);
            action = 'ajaxregisterstudent';
            security = $('#stud_signonsecurity').val();
            resume = $('#uploadResume').val();
            password = $('#stud_signonpassword').val();
            email = $('#stud_email').val();
        ctrl = $(this);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_auth_object.ajaxurl,
            data: {
                'action': action,
                'password': password,
                'email': email,
                'security': security,
                'resume': resume,
            },
            success: function (data) {
                $('p.status', ctrl).text(data.message);
                if (data.loggedin == true) {
                    document.location.href = ajax_auth_object.redirecturl;
                } 
            },
            error: function() {
            }
        });
        e.preventDefault();
    });

我在functions.php中的功能:

function ajax_auth_init(){
    wp_register_script('ajax-auth-script', get_stylesheet_directory_uri() . '/library/js/ajax-auth-script.js', array('jquery') );
    wp_enqueue_script('ajax-auth-script');
    wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'redirecturl' => site_url() . "/wp-admin/", //redirect_login_page() <-- when user logs in, it will go to the wp-admin and then this function will check to see where they should go
        'loadingmessage' => __('Sending user info, please wait...')
    ));
    // Enable the student user with no privileges to run ajax_register() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxregisterstudent', 'ajax_register_student' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_auth_init');
}

function ajax_register_student(){
    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'stud-ajax-register-nonce', 'security' );
    $email = $_POST["email"];
    $resume = $_POST["resume"];
    $password = $_POST["password"];
    $verify = $_POST["verify"];
    $info = array(
          'user_pass'   =>  $password,
          'user_login'  =>  $email,
          'user_email'  =>  $email,
          'user_nicename'  =>   $email,
      );
    // Register the user
    $user_register = wp_insert_user( $info );
        //assign media to user
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
        require_once( ABSPATH . 'wp-admin/includes/media.php' );
        // Let WordPress handle the upload.
        $img_id = media_handle_upload( 'resume', 0 );
        if ( !is_wp_error( $img_id ) ) {
            //assign author to media
            $arg = array(
                'ID' => $img_id,
                'post_author' => $user_register,
            );
            wp_update_post( $arg );
            //assign media to author
            update_user_meta( $user_register, 'qd_resume', $img_id );
        }
    if ( is_wp_error($user_register) ){
        $error  = $user_register->get_error_codes() ;
        // echo $user_register->get_error_message();
        if(in_array('empty_user_login', $error))
            echo json_encode(array('loggedin'=>false, 'message'=>__($user_register->get_error_message('empty_user_login'))));
        elseif(in_array('existing_user_login',$error))
            echo json_encode(array('loggedin'=>false, 'message'=>__('This username is already registered.')));
        elseif(in_array('existing_user_email',$error))
        echo json_encode(array('loggedin'=>false, 'message'=>__('This email address is already registered.')));
    }
    else {
      auth_user_login($info['user_login'], $info['user_pass'], 'Registration');
    }
    die();
}

如果我评论以下条件:如果抓取$ img_id没有错误,我对qd_resume meta_key的meta_value有此错误,我不明白为什么它不会抓取文件

o:8:" wp_error":4:{s:6:" errors"; a:1:{s:12:" upload_error"; a:1:{i:0:0:0; s:212:"文件file file file file 是空的。请上传一些更重要的东西。这个错误可能 也是由于上传在您的php.ini或 post_max_ize被定义为小于upload_max_filesize php.ini。";}}} s:10:" error_data"; a:0:{} s:2:" id"; i:0; i:0; s:6:" filter"; s:3; s:3:" raw";}

/*************************************************
AUTHORIZE LOGIN
**************************************************/
function auth_user_login($user_login, $password, $login)
{
    $info = array();
    $info['user_login'] = $user_login;
    $info['user_password'] = $password;
    $info['remember'] = true;
    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
    } else {
        wp_set_current_user($user_signon->ID); 
        echo json_encode(array('loggedin'=>true, 'message'=>__($login.' successful, redirecting...')));
    }
    die();
}
/***********************************************************************************
// Deal with images uploaded from the front-end while allowing ACF to do it's thing
**************************************************************************************/
function my_acf_pre_save_post($user_register) {
    if ( !function_exists('wp_handle_upload') ) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once( ABSPATH . 'wp-admin/includes/media.php' );
    }
    // Move file to media library
    // $movefile = wp_handle_upload( $_FILES['uploadResume'], array('test_form' => false) );
    $movefile = wp_handle_upload( $_FILES['resume'], array('test_form' => false) );
    // If move was successful, insert WordPress attachment
    if ( $movefile && !isset($movefile['error']) ) {
        $wp_upload_dir = wp_upload_dir();
        $attachment = array(
            'guid' => $wp_upload_dir['url'] . '/' . basename($movefile['file']),
            'post_mime_type' => $movefile['type'],
            'post_title' => preg_replace( '/.[^.]+$/', ”, basename($movefile['file']) ),
            'post_content' => ”,
            'post_status' => 'inherit'
        );
        $attach_id = wp_insert_attachment($attachment, $movefile['file']);
        // Assign the file as the featured image
        // set_post_thumbnail($post_id, $attach_id);
        // update_field('uploadResume', $attach_id, $post_id);
        update_user_meta( $user_register, 'qd_resume', $attach_id );
    }
    return $user_register;
}
add_filter('acf/pre_save_post' , 'my_acf_pre_save_post');

而不是提供现成的解决方案,我会为您提供与Ajax请求一起提交文件的步骤。

  • 您已经在注册表中包含了文件输入。
  • 您需要formdata对象而不是键/值对象才能通过ajax请求中的文件传递。
  • 在服务器上,您可以使用WordPress API(wp_handle_upload/Media_handle_upload(或普通php保存文件。

因此,基本上您需要将FormData附加到对象上。下面的此脚本可能会帮助您。

var uploadResume = document.getElementById('uploadResume');
var formdata = new FormData();
formdata.append('resume ', uploadResume.files[0]);
formdata.append('action', 'ajaxregisterstudent');
//Append security, password, email etc.
//...
$.ajax({
    type: 'POST',
    dataType: 'json',
    data: formdata,
    success: ...

我不确定在服务器端代码中如何实现ACF。但是,希望这将帮助您朝着正确的方向发展。

参考:https://developer.mozilla.org/en-us/docs/web/api/formdata/using_formdata_objectshttps://www.ibenic.com/wordpress-file-upload-with-ajax/

免责声明:我是此处提到的TUTS博客文章的作者。

最新更新