1

I have added an email input / form to my Wordpress page and want to collect the information from this as JSON data.

The HTML code is:

<form method="get"><p id="myform"><input type="email" name="EMAIL" placeholder="enter email address" required />
<input id="submit" type="submit" value="Sign up" /></p></form>

The php, which is in my functions.php file, is:

if (isset($_POST['submit'])) {
$file = "data.json";
$json_string = json_encode($_POST, JSON_PRETTY_PRINT);
file_put_contents($file, $json_string, FILE_APPEND);
}

I have a data.json file, which is being referenced in the php part of the above code, which sits at the first level of my child theme.

I'm not getting any error messages, and the input field is allowing email addresses to be input, but the data isn't going to my data.JSON file.

I can't seem to work out why?

Any help would be fab.

Emily

1 Answer 1

0

I have checked the code. file_put_contents function accepts the absolute path for the file. Use the 'get_template_directory()' function for the absolute path. Please check the updated code.

<form method="get"><p id="myform"><input type="email" name="EMAIL" placeholder="enter email address" required /> <input id="submit" name="submit" type="submit" value="Sign up" /></p></form>



if (isset($_POST['submit'])) {
$file = get_template_directory() . '/data.json';
$json_string = json_encode($_POST, JSON_PRETTY_PRINT);
file_put_contents($file, $json_string, FILE_APPEND);
}

Note: Code is writing all POST data into the json file. If you just want email address then change json_encode($_POST, JSON_PRETTY_PRINT); into json_encode($_POST['EMAIL'], JSON_PRETTY_PRINT);

Cheers :)

4
  • Hi Ashikra, thanks for the above, it still doesn't work though :(
    – pjk_ok
    Nov 20, 2016 at 23:34
  • are you using the code under theme functions.php ? and where you put the data.json file I mean url ? Nov 21, 2016 at 0:05
  • yes, the php code is in my child theme's functions.php file and the data.json file is in the root of my child theme i.e. childtheme/data.json It's a shame the site is on localhost, hence me not being able to post a link.
    – pjk_ok
    Nov 21, 2016 at 1:01
  • @Emily Chewy I have updated the code. You missed the name attribute of the submit button and that why if condition not worked. If still not works I need your functions.php file. Nov 21, 2016 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.