Home > Mobile >  WordPress shortcode for output form
WordPress shortcode for output form

Time:08-16

I wanna create a form with a shortcode so I can use it wherever I need it. I use the below minimal example:

add_shortcode( 'form', 'create_form' );
function create_form () {
    require_once __DIR__ . '/form.php';
}

But when I add the shortcode on the post and try to save it, it shows an error: ‘Updating failed. The response is not a valid JSON response.’

I have also noticed that WordPress specifies this:

shortcode should never produce an output of any kind

https://developer.wordpress.org/reference/functions/add_shortcode/

There are tons of plugins using the shortcode and outputting something especially some of them are very popular plugins. So they are all doing wrong?

If the shortcode is not meant for making such a task, how do I make a form and add it somewhere? Or the shortcode is okay but I misunderstood and doing something wrong?

Update: The form.php is very simple and looks like this:

<label for="fname">First name:</label>
<input type="text" id="fname" name="fname">
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname">

CodePudding user response:

The documentation says to return something. But, the create_form() function does not return anything. The content of form.php should be return-ed as a string rather than only require-ed.

For example:

add_shortcode( 'form', 'create_form' );
function create_form () {
    $form_filepath = __DIR__ . '/form.php';
    $form_html = file_get_contents( $form_filepath );
    return $form_html;
}
  • Related