Form display in new page

时间:2017-08-08 作者:Prakash

我是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文件运行。

1 个回复
SO网友:Valérian Polizzi

尝试创建新页面并将[elh db insert]作为内容。

如果要使用[插入db]作为shorcode,则应更改

添加\\u短代码(\'elh-db-insert\',\'elh\\u insert\\u into\\u db\');

add\\u shortcode(\'insert-into-db\',\'elh\\u insert\\u into\\u db\');

结束

相关推荐

Call another page in forms

我正在为WordPress插件做一些练习。在插件中,我正在处理一个表单,我需要的是在提交时调用另一个页面。我试过了,但似乎什么都没用。<form method = \"Post\" action = \"some_file.php\"> </form>