3

I have a plugin, a cron job runs refresh_my_plugin() daily.

I need a button on my plugins Settings/option page, allowing a user to manually run said function, and I want it inline, with ajax.

I've got the following, which should work - but how would I add Wordpress Nonces to it?

<?php 
    if (isset($_POST['refresh_my_plugin'])) {
        refresh_my_plugin();
    }

    function refresh_my_plugin() {
        // main function, runs daily with cron
        return true;
    }
?>

<button id='refresh'>Refresh My Plugin</button>

<script>
    jQuery('#refresh').click(function(){
        $.ajax({
            type: 'post',
            data: { "refresh_my_plugin": "now"},
            success: function(response) { 
                jQuery('#refresh').text("Successfully Refreshed!");
            },
            error: function(response) { 
                jQuery('#refresh').text("...error!");
            },
        });
    });
</script>
2

I figured it out. Simply, in my request, under data, I added

"nonce" : "<?php echo wp_create_nonce( 'refresh_my_plugin' ); ?>"

then to verify

if (isset($_POST['refresh_my_plugin']))
    if ( wp_verify_nonce( $_POST['nonce'], 'refresh_my_plugin' ) )
        refresh_my_plugin();

With incorrect wp_verify_nonce, I instead get a 403, which is reflected on the button with the error handler.

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.