我是wordpress的新手,我正在尝试创建一个新表并将表单数据保存到其中。我有以下代码。我创建了一个儿童主题。功能。php:
function elh_insert_into_db() {
global $wpdb;
// creates my_table in database if not exists
$table = $wpdb->prefix . "my_table";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
UNIQUE (`id`)
) $charset_collate;";
require_once( ABSPATH . \'wp-admin/includes/upgrade.php\' );
dbDelta( $sql );
// starts output buffering
ob_start();
?>
<form action="#v_form" method="post" id="v_form">
<label for="visitor_name"><h3>Hello there! What is your name?</h3></label>
<input type="text" name="visitor_name" id="visitor_name" />
<input type="submit" name="submit_form" value="submit" />
</form>
<?php
$html = ob_get_clean();
// does the inserting, in case the form is filled and submitted
if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] != "" ) {
$table = $wpdb->prefix."my_table";
$name = strip_tags($_POST["visitor_name"], "");
$wpdb->insert(
$table,
array(
\'name\' => $name
)
);
$html = "<p>Your name <strong>$name</strong> was successfully recorded. Thanks!!</p>";
}
// if the form is submitted but the name is empty
if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] == "" )
$html .= "<p>You need to fill the required fields.</p>";
// outputs everything
return $html;
}
// adds a shortcode you can use: [insert-into-db]
add_shortcode(\'elh-db-insert\', \'elh_insert_into_db\');
add_action( \'wp_enqueue_scripts\', \'my_child_theme_scripts\' );
function my_child_theme_scripts() {
wp_enqueue_style( \'parent-theme-css\', get_template_directory_uri() . \'../twentyseventeen/style.css\' );
}
?>
我如何查看此表单。激活此主题时,我看到的只是父主题。如何显示此表单并创建表?保存后,如何将数据显示到模板中?有人能帮我吗?我想了解什么时候起作用。php文件运行。