Skip to content

Instantly share code, notes, and snippets.

@rwsite
Last active December 21, 2022 22:48
Show Gist options
  • Save rwsite/eb9a4b52a4cc11c128fa54ab059ace4d to your computer and use it in GitHub Desktop.
Save rwsite/eb9a4b52a4cc11c128fa54ab059ace4d to your computer and use it in GitHub Desktop.
WP AJAX Example class
<?php
// WP AJAX example
class WP_AJAX_Example{
/**
* Add WP actions. Must be called only once.
* @return void
*/
public function add_actions(){
$actions = [
'ajax_get_clients',
// you can add other php handler functions here
];
foreach ($actions as $action) {
add_action('wp_ajax_' . $action, $action, 10, 1);
add_action('wp_ajax_nopriv_' . $action, $action, 10, 1);
}
add_action('wp_dashboard_setup', [$this, 'wp_dashboard_setup']);
}
/**
* AJAX handler. Function name equals $actions[]
*
* @return void
*/
public function ajax_get_clients()
{
$nonce = $_REQUEST['nonce'];
$data = $_REQUEST['data'];
if (!wp_verify_nonce($nonce, 'ajax')) {
trigger_error('verify failed in ' . __FUNCTION__);
wp_send_json_error();
}
// do something
$result = true || false;
if ($result) {
wp_send_json_success($result);
}
wp_send_json_error($result);
}
/**
* Render wp dashboard widget
*
* @return void
*/
public function wp_dashboard_setup() {
if (!current_user_can('manage_options')) {
return;
}
wp_add_dashboard_widget('ajax', __('AJAX', 'wp'), [$this, 'html']);
}
/**
* Render html button and add js for them.
*
* @return void
*/
public function html()
{
?>
<button type="button" class="ajax button button-primary" data-action="ajax_get_clients"
data-nonce="<?= wp_create_nonce('ajax') ?>"> AJAX button
</button>
<script type="application/javascript">
jQuery(document).ready(function ($) {
$('.ajax').on('click', function (event) {
event.preventDefault();
let $this = $(this).removeClass('success').removeClass('error').addClass('loading');
$.ajax({
type: 'POST',
url: '/admin-ajax.php',
data: {
'action': $(this).data('action'),
'data': '', // any data for php
'nonce': $(this).data('nonce')
},
success: function (response) {
console.log('ajax', response);
if (response.success) {
$this.removeClass('loading').addClass('success');
} else {
$this.removeClass('loading').addClass('error');
}
},
});
});
});
</script>
<?
}
}
// run this code, if you include it as file
(new WP_AJAX_Example())->add_actions();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment