您好,我正在开发WP插件,正在从表单获取值并将其保存到数据库。它不起作用,除非我在save_form_values函数上使用admin-init挂钩。请参阅下面的代码:
function save_form_values() {
if (($_SERVER['REQUEST_METHOD'] == 'POST') ){
global $wpdb;
$delegate_name = trim($_POST['delegate_name']);
$certificate_id = trim($_POST['certificate_id']);
$training_course = trim($_POST['training_course']);
$company = trim($_POST['company']);
$startdate = trim($_POST['startdate']);
$enddate = trim($_POST['enddate']);
$expirationdate = trim($_POST['expirationdate']);
$table_name = $wpdb->prefix . 'certificat';
$wpdb->insert( $table_name, array(
'nom' => $delegate_name,
'numero' => $certificate_id,
'idformation' => $training_course,
'idsociete' => $company,
'date_formation' => $enddate,
'date_expiration' => $expirationdate
) );
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
if($_FILES['trainee_image']['name']) {
if(!$_FILES['trainee_image']['error']) {
//validate the file
$new_file_name = strtolower($_FILES['trainee_image']['tmp_name']);
//can't be larger than 200 KB
if($_FILES['trainee_image']['size'] > (200000)) {
//wp_die generates a visually appealing message element
wp_die('Your file size is to large.');
}
else {
//the file has passed the test
//These files need to be included as dependencies when on the front end.
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.
// Remember, 'upload' is the name of our file input in our form above.
$file_id = media_handle_upload( 'trainee_image', 0 );
if ( is_wp_error( $file_id ) ) {
wp_die('Error loading file!');
}
}
}
else {
//set that to be the returned message
wp_die('Error: '.$_FILES['trainee_image']['error']);
}
}
}
}
这在我这样做时有效:
add_action( 'admin_init', 'save_form_values' );
我需要代码才能正常运行。谁能帮忙吗?