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>

1 Answer
1

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.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *