0

I'd like to use transient for my widget. User can choose for how long data can be cached (1, 2, 10 hours). I also want to add a button Refresh now inside a widget form.

I don't know how to call delete_transient on click.

I was thinking to create some hidden input (<input type="hidden" name="refresh-data" value="0" />). Set 1 if the button was clicked. Check it inside function widget() and call delete_transient if needed. But I think I can't set 0 to refresh-data inside widget function.

1

I assume the widget and the "Refresh now" button are shown on the front-end, yes? One option to delete a transient is to use ajax to do it.

This is rather rough example, but I hope it gives you the idea what to do. You can read more about Ajax in WordPress from the codex.

// In your php file
add_action( 'wp_ajax_my_delete_transient_action', 'my_delete_transient_action' );
add_action( 'wp_ajax_nopriv_my_delete_transient_action', 'my_delete_transient_action' ); // for users that are not logged in

function my_delete_transient_action() {

    // Check nonce and other stuff here as needed
    // If and when everything is ok, then use the delete_transient function
    $deleted = delete_transient('my_user_specific_transient'); // returns bool

    // Option 1 to send custom text response back to front-end
    if ($deleted) {
        echo 'Transient deleted';
    } else {
        echo 'Transient deletion failed';
    } 
    die();

    // Option 2
    if ($deleted) {
        wp_send_json_success('Transient deleted');
    } else {
        wp_send_json_error('Transient deletion failed');
    }

}

// In your js file
jQuery(document).ready(function($) {
    $('.my-reset-button').on('click',function(event){
        event.preventDefault();
        var data = {
            'action': 'my_delete_transient_action',
        };

        // You can use wp_localize_script in php file to have admin_url( 'admin-ajax.php' ) available in front-end
        jQuery.post(ajax_object.ajax_url, data, function(response) {
            alert('Got this from the server: ' + response); // do something with the response
        });
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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