Skip to content

Instantly share code, notes, and snippets.

@VicVicos
Created May 3, 2017 08:23
Show Gist options
  • Select an option

  • Save VicVicos/81550626cbbffaeb8d28f043031c0675 to your computer and use it in GitHub Desktop.

Select an option

Save VicVicos/81550626cbbffaeb8d28f043031c0675 to your computer and use it in GitHub Desktop.
Ajax WP OOP habrahabr.ru/company/dataart/blog/271189/
abstract class AJAX_Handler {
function __construct($action_name) {
$this->init_hooks($action_name);
}
public function init_hooks($action_name) {
add_action('wp_ajax_'.$action_name , array($this,'callback'));
add_action('wp_ajax_nopriv_'.$action_name, array($this,'callback_nopriv'));
}
public function callback_nopriv() {
$this->callback();
}
abstract public function callback();
}
new Something('do_something');
function js_variables() {
$variables = array (
'ajax_url' => admin_url('admin-ajax.php'),
'is_mobile' => wp_is_mobile()
// Тут обычно какие-то другие переменные
);
echo '<script type="text/javascript">window.wp_data = ' . json_encode($variables) . ';</script>';
}
add_action('wp_head', 'js_variables');
jQuery(function($){
$.ajax({
type: "GET",
dataType: 'json',
url: window.wp_data.ajax_url,
data: {
action : 'do_something'
},
success: function (response) {
console.log('AJAX response : ',response);
}
});
});
<?php
class Something extends AJAX_Handler
{
function callback ()
{
wp_send_json_success(['test' => 'Works!']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment