在wordpress中提交一个web表单


Submiting a web form in wordpress

我是wordpress的新手,我在处理简单的表单布局/提交时遇到了一些困难。我有一个页面(从wp-admin页面创建),其中包含以下代码:

<div class="container-fluid">
    <form class="form-horizontal" action="" method="POST" >
        <div class="row form-group">
            <div class="col-xs-12">
                <label for="name">Nome</label>
                <input type="text" class="form-control" id="name" name="name" />
            </div>
        </div>
        <div class="row form-group">
            <div class="col-xs-12">
                <label for="residence">Residência</label>
                <input type="text" name="residence" id="residence" />
            </div>
        </div>
        <div class="row form-group">
            <div class="col-sm-6">
                <input class="btn btn-default" type="submit" value="Registar">
            </div>
        </div>
    <form>
</div>

我这里的问题是,我不知道什么放在动作属性和如何处理表单之后。我试图在模板文件夹中创建一个php文件,并将其放在行动中,但它根本不起作用。我也看到了一些可以添加到functions.php的操作,但我不认为这是解决问题的最佳方案。我想要的只是提交表单,将其作为元数据存储在数据库中,并将用户重定向到主页。

我的建议是使用action="#",它在用户按提交时将用户重定向到当前页面。然后,您可以检查隐藏字段,该字段不显示表单,而是检查数据并将其存储在数据库中,然后将用户重定向到主页。

你可以把这个文件放在Wordpress安装的任何地方(只要你的用户可以访问它)。如果可移植性不是问题,就把它放在根目录中,或者查找制作页面模板文件,如果可移植性很重要。

另外,小心使用属性name="name",因为这混淆了你的Wordpress页面处理,我似乎记得(Wordpress使用它来识别它在什么页面上)。

下面是相同页面处理的示例:

<?php 
if (isset($_POST["formSubmitted"])) {
    $name = $_POST["formName"];
    $residence = $_POST["formResidence"];
    // do database work here with $name and $residence
    // then output javascript to redirect to main page
    echo '<script>window.location = "http://example.com";</script>';
} else {
    // we display the form
?>
<div class="container-fluid">
    <form class="form-horizontal" action="#" method="POST" >
        <div class="row form-group">
            <div class="col-xs-12">
                <label for="name">Nome</label>
                <input type="text" class="form-control" id="name" name="formName" />
            </div>
        </div>
        <div class="row form-group">
            <div class="col-xs-12">
                <label for="residence">Residência</label>
                <input type="text" name="formResidence" id="residence" />
            </div>
        </div>
        <div class="row form-group">
            <div class="col-sm-6">
                <input class="btn btn-default" type="submit" value="Registar">
            </div>
        </div>
    <input type="hidden" name="formSubmitted" value="1">
    </form>
</div>
<?php
}
?>

另一种解决方案是使用get_stylesheet_directory_uri(),它返回主题样式表所在的目录。你可以这样使用:

<form action="<?php echo get_stylesheet_directory_uri()."/some_php_file.php"; ?>" method="POST">

然后将数据传递给该文件,您可以从中将其添加到数据库中。

如果你是初学者,为什么不直接使用contact form 7或gravity form呢?

联系表格7:http://contactform7.com/

Gravity Forms: http://www.gravityforms.com/