Поэтому я пытаюсь создать пользовательскую форму регистрации, где пользователи также могут загружать файлы (например, резюме), используя AJAX и Modal.
Я нашел это руководство, которое позволит мне это сделать, но проблема в том, что я не уверен, как я могу загрузить файлы, которые также будут подключаться к ACF.
http://fellowtuts.com/wordpress/wordpress-ajax-login-and-register-without-a-plugin/
Мне удалось сделать это с помощью этого обсуждения, но это работает, только если я не использую AJAX:
https://wordpress.stackexchange.com/questions/282586/acf-upload-image-in-front-end-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 не было ошибки, у моего meta_value для метаданного qd_resume есть эта ошибка, и я не мог понять, почему он не будет захватывать файл
O: 8: "WP_Error": 4: {s: 6: "ошибка"; а: 1: {s: 12: "upload_error"; а: 1: {я: 0; s: 212: "Файл
пустой. Пожалуйста, загрузите что-нибудь более существенное. Эта ошибка может
также может быть вызвано отключением загрузки в вашем php.ini или
Значение post_max_size меньше, чем значение upload_max_filesize в
. Php.ini ";}} s: 10:" error_data "; а: 0: {} s: 2:" ID "; я: 0; s: 6:" фильтр "; s: 3:" сырой "; }
/*************************************************
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');