What i am trying to do is to have this function working within my plugin block of code without having it as plugin on it own.
My current and working solution outside wordpress is
Save contents
$KeepText="$name||$Phone||";
$dataHolder="keepdata.txt";
$file = fopen($dataHolder,"w");
if(fwrite($file, $KeepText)){echo "Data Saved Successfully !";}
else{echo "Error Occur !";}
fclose($file);
Retrieve data
$dataHolder="keepdata.txt";
$dataPool=file($dataHolder);
$TextPool=explode("||", (string)$dataPool[0]);
if ($dataPool) {
$ContactName=$TextPool[0];
$ContactPhone = $TextPool[1];
}
Output //ContactName //ContactPhone
The logic will perfectly print out all required data.
However doing the same thing within WordPress generate errors or not even echoing out datas.
I have came across recommended solutions which suggested using the WP_Filesystem . From This Website I have tried it in which it work fine as a standalone Plugin . But that is not the solution I want.
What I will like to do is have the wp_filesystem like this without admin_menu().
function filesystem_init($form_url, $method, $context, $fields = null) {
global $wp_filesystem;
if (false === ($creds = request_filesystem_credentials($form_url, $method, false, $context, $fields))) {
return false;
}
if (!WP_Filesystem($creds)) {
request_filesystem_credentials($form_url, $method, true, $context);
return false;
}
return true;
}
And later have the function dataTosave(){}
like the below
function dataTosave($form_url){
global $wp_filesystem;
check_admin_referer('contact_form');
$contactname = sanitize_text_field($_POST['contactname']);
$contactphone = sanitize_text_field($_POST['contactphone']);
$form_fields = array('contactname','contactphone');
$method = '';
$context = WP_PLUGIN_DIR . '/keepdata';
$form_url = wp_nonce_url($form_url, 'contact_form');
if(!filesystem_init($form_url, $method, $context, $form_fields))
return false;
$target_dir = $wp_filesystem->find_folder($context);
$target_file = trailingslashit($target_dir).'/keepdata.txt';
$dataTosave=$contactname."||".$contactphone."||";
if(!$wp_filesystem->put_contents($target_file, $dataTosave, FS_CHMOD_FILE))
return new WP_Error('writing_error', 'Error when writing file');
return "Data Saved";
}
Once the form is post
if(isset($_POST['contactform_submit'])){
dataTosave();
//new submission run the function
}
<form method="post" action="" >
<?php wp_nonce_field('contact_form'); ?>
<label for="contactname">Contact Name</label><br>
<input id="contactname" name="contactname" value="<?php echo $_POST['contactname']?>" require >
<label for="contactphone">Contact Phone</label><br>
<input id="contactphone" name="contactphone" value="<?php echo $_POST['contactphone']?>" required >
<?php submit_button('Submit', 'primary', 'contactform_submit', true);?>
</form>
I have do it like this but no luck .Thanks