I try to make a form with shortcode.
Main plugin file:
require "functions.php";
function form_shortcode(){
ob_start();
include "form.php";
return ob_get_clean();
}
add_shortcode( "form", "form_shortcode" );
form.php:
<form action="<?= $_SERVER["REQUEST_URI"]; ?>" method="post">
<label for="id">ID</label>
<input id="id" name="id" type="text" value="" required />
<input type="submit" name="submitid" value="Submit">
</form>
functions.php:
if ( isset( $_POST["submitid"] ) ) {
echo "<p>OK</p>";
}
I place shortcode into the middle of website: <div class="wrap">[form]</div>
But after submitting I get <p>OK</p>
before <!DOCTYPE html><html>
instead of <div class="wrap"><p>OK</p></div>
What's wrong? After a long googling I found something about buffers, so tried to add ob_start();
and ob_get_clean();
but no effect. :(
I try to make a form with shortcode.
Main plugin file:
require "functions.php";
function form_shortcode(){
ob_start();
include "form.php";
return ob_get_clean();
}
add_shortcode( "form", "form_shortcode" );
form.php:
<form action="<?= $_SERVER["REQUEST_URI"]; ?>" method="post">
<label for="id">ID</label>
<input id="id" name="id" type="text" value="" required />
<input type="submit" name="submitid" value="Submit">
</form>
functions.php:
if ( isset( $_POST["submitid"] ) ) {
echo "<p>OK</p>";
}
I place shortcode into the middle of website: <div class="wrap">[form]</div>
But after submitting I get <p>OK</p>
before <!DOCTYPE html><html>
instead of <div class="wrap"><p>OK</p></div>
What's wrong? After a long googling I found something about buffers, so tried to add ob_start();
and ob_get_clean();
but no effect. :(
- Where were you expecting the OK to appear? If you put it at the top level of the plugin's functions.php outside of an action handler then it'll be written to the page as the plugin is loaded, which is probably before you intended. – Rup Commented Oct 25, 2020 at 23:49
1 Answer
Reset to default 1Change form.php
<form action="<?= $_SERVER["REQUEST_URI"]; ?>" method="post">
<input type="hidden" name="form_submit_nonce" value="<?php echo wp_create_nonce('form-submit-nonce'); ?>"/>
<label for="id">ID</label>
<input id="id" name="id" type="text" value="" required />
<input type="submit" name="submitid" value="Submit">
</form>
Change plugin file
function form_shortcode(){
if ( isset( $_POST["submitid"] ) && isset($_POST['form_submit_nonce']) && wp_verify_nonce($_POST['form_submit_nonce'], 'form-submit-nonce') ) {
echo "<p>OK</p>";
} else {
include "form.php";
}
}
add_shortcode( "form", "form_shortcode" );