japhfortin
japhfortin

Reputation: 361

WP Options API Custom Action After Form Submit

I'm sorry if this is an old question but I really can't find answer for this. I am new to wordpress plugin development. How can I do a somewhat like a callback before a form is submitted using WP Options API? In a native PHP, we can just say as

if (isset($_POST['submit'])) {
    $options = $_POST['zt_ftp_settings'];
    var_dump($options);
 } 

However, I am using the WP Options API. It saves the data correctly, I just want to do some more after saving the data.

Here is what I did,

<form method="post" action="options.php">
<?php   
settings_fields('zt_ftp_settings_options' );
do_settings_sections( 'zt_ftp_settings_options' );
$option = get_option('zt_ftp_settings');
?>
<h2>FTP Settings</h2>
<p>Please provide your ftp credentials.</p>
<table class="form-table">
    <tbody>
            <tr>
                <th scope="row">FTP Hostname</th>
                <td>
                    <input name="zt_ftp_settings[zt_ftp_host_name]" type="text" id="zt_ftp_host_name" value="<?php echo $option['zt_ftp_host_name']?>" class="regular-text">
                </td>
            </tr>
            <tr>
                <th scope="row">FTP Username</th>
                <td>
                    <input name="zt_ftp_settings[zt_ftp_user_name]" type="text" id="zt_ftp_user_name" value="<?php echo $option['zt_ftp_user_name']?>" class="regular-text">
                </td>
            </tr>
            <tr>
                <th scope="row">FTP Password</th>
                <td>
                    <input name="zt_ftp_settings[zt_ftp_password]" type="password" id="zt_ftp_password" value="<?php echo $option['zt_ftp_password']?>" class="regular-text">
                </td>
            </tr>
    </tbody>
</table>
<?php submit_button( 'Save Settings' ); ?>

Thanks.

Upvotes: 0

Views: 1520

Answers (1)

Gnanasekaran Loganathan
Gnanasekaran Loganathan

Reputation: 1108

Use WP AJAX functionality.

Use below JS,

 $("#submit").click(function(){ 
    var url = window.location.href;

    jQuery.post(
        ajaxurl, 
        {
            'action': 'delete_search',
            'tid':   tid,
        },
        function(response){
          location.reload();
        });
 });

Replace your submit button ID and use your form values.

Use below code in function.php

function prefix_ajax_delete_search() {
    global $wpdb;
    $user_id = get_current_user_id();
    $wpdb->delete('sf_save_search', array('id' => $_POST['tid']) ); 
    wp_die();
}
add_action( 'wp_ajax_delete_search', 'prefix_ajax_delete_search' );

As per your requirement change the function name and variables

Upvotes: 1

Related Questions