在使用 AJAX 和 ACF 注册 WordPress 后向用户上传文件
Uploading files to a user upon WordPress registration with AJAX and ACF
所以我正在尝试创建一个自定义注册表单,用户还可以使用 AJAX 和模式上传文件(即简历)。
我发现这个教程可以让我这样做,但问题是,我不确定如何上传也将连接到 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();
}
如果我注释掉如果抓取$[=38=没有错误的条件,我的meta_value对于qd_resumemeta_key有这个错误,并且我不明白为什么它不抓取文件
O:8:"WP_Error":4:{s:6:"errors";a:1:{s:12:"upload_error";a:1:{i:0;s:212:"File
is empty. Please upload something more substantial. This error could
also be caused by uploads being disabled in your php.ini or by
post_max_size being defined as smaller than upload_max_filesize in
php.ini.";}}s:10:"error_data";a:0:{}s:2:"ID";i:0;s:6:"filter";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 对象而不是 key/value 对象来在 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: ...
我不确定 what/how 您是否在服务器端代码中实施了 ACF。不过,希望这能帮助您找到正确的方向。
参考:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://www.ibenic.com/wordpress-file-upload-with-ajax/
免责声明:我是此处提到的 Fellow Tuts 博客 post 的作者。
所以我正在尝试创建一个自定义注册表单,用户还可以使用 AJAX 和模式上传文件(即简历)。
我发现这个教程可以让我这样做,但问题是,我不确定如何上传也将连接到 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();
}
如果我注释掉如果抓取$[=38=没有错误的条件,我的meta_value对于qd_resumemeta_key有这个错误,并且我不明白为什么它不抓取文件
O:8:"WP_Error":4:{s:6:"errors";a:1:{s:12:"upload_error";a:1:{i:0;s:212:"File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.";}}s:10:"error_data";a:0:{}s:2:"ID";i:0;s:6:"filter";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 对象而不是 key/value 对象来在 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: ...
我不确定 what/how 您是否在服务器端代码中实施了 ACF。不过,希望这能帮助您找到正确的方向。
参考: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects https://www.ibenic.com/wordpress-file-upload-with-ajax/
免责声明:我是此处提到的 Fellow Tuts 博客 post 的作者。