据我所知,您的数据库中已有该表。
我不知道你是如何给它命名的,但最好的做法(对我来说是一个必须做的练习)是用相同的wordpress表前缀命名,这是在wp-config.php
.
你也没有说这个表是如何构造的,但我猜它是这样的:
ID (integer,primary,autoincrement) | name (varchar) | phone (varchar) | email (varchar)
您可以添加打印表单的快捷码。在您的
functions.php
添加:
add_action(\'init\', function() {
add_shortcode(\'userform\', \'print_user_form\');
});
function print_user_form() {
echo \'<form method="POST">\';
wp_nonce_field(\'user_info\', \'user_info_nonce\', true, true);
?>
All your form inputs (name, email, phone) goes here.
<?php
submit_button(\'Send Data\');
echo \'</form>\';
}
现在只需在wp dashboard中创建一篇文章或一个页面,然后简单地添加
[userform]
: 表单在页面中神奇地显示为printend。
如您所见,我没有将action属性添加到表单中,表单通过这种方式将post数据发送到同一页面。
现在您必须保存数据。在早期挂钩上添加操作,查找$_POST
, 检查nonce并保存数据:
add_action(\'template_redirect\', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST[user_info_nonce]) &&
wp_verify_nonce($_POST[user_info_nonce], \'user_info\')
) {
// you should do the validation before save data in db.
// I will not write the validation function, is out of scope of this answer
$pass_validation = validate_user_data($_POST);
if ( $pass_validation ) {
$data = array(
\'name\' => $_POST[\'name\'],
\'email\' => $_POST[\'email\'],
\'phone\' => $_POST[\'phone\'],
);
global $wpdb;
// if you have followed my suggestion to name your table using wordpress prefix
$table_name = $wpdb->prefix . \'my_custom_table\';
// next line will insert the data
$wpdb->insert($table_name, $data, \'%s\');
// if you want to retrieve the ID value for the just inserted row use
$rowid = $wpdb->insert_id;
// after we insert we have to redirect user
// I sugest you to cretae another page and title it "Thank You"
// if you do so:
$redirect_page = get_page_by_title(\'Thank You\') ? : get_queried_object();
// previous line if page titled \'Thank You\' is not found set the current page
// as the redirection page. Next line get the url of redirect page:
$redirect_url = get_permalink( $redirect_page );
// now redirect
wp_safe_redirect( $redirect_url );
// and stop php
exit();
}
}
});
代码很粗糙,但应该是一个有效的起点。内联注释可以帮助您理解工作流。
请务必阅读文档: