Skip to content

Instantly share code, notes, and snippets.

@miya0001
Created March 3, 2012 17:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miya0001/1967049 to your computer and use it in GitHub Desktop.
Save miya0001/1967049 to your computer and use it in GitHub Desktop.
WordPressでちょっとだけ簡単にAjax
<?php
if (!class_exists('WP_AdminAjax')):
class WP_AdminAjax {
private $nonce;
function __construct($action, $callback, $nopriv = false, $nonce = false)
{
if (preg_match('/^[a-zA-Z0-9_\-]+$/', $action)) {
$this->action = $action;
} else {
wp_die("Invalid strings for \$action.");
}
$this->callback = $callback;
if ($nonce) {
$this->nonce = $nonce;
} else {
$this->nonce = $action;
}
add_action('wp_ajax_'.$action, array(&$this, 'wp_ajax'));
if ($nopriv) {
add_action('wp_ajax_nopriv_'.$action, array(&$this, 'wp_ajax'));
}
}
public function get_url($query = array())
{
$query['action'] = $this->action;
$query['nonce'] = $this->get_nonce();
$url = admin_url("admin-ajax.php");
foreach ($query as $key => $value) {
$url = add_query_arg($key, $value, $url);
}
return $url;
}
public function get_nonce()
{
return wp_create_nonce($this->nonce);
}
public function wp_ajax()
{
nocache_headers();
if (wp_verify_nonce($_GET["nonce"], $this->nonce)) {
$res = call_user_func($this->callback);
if (is_array($res)) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($res);
} else {
echo $res;
}
} else {
header('HTTP/1.1 403 Forbidden');
echo '{}';
}
exit;
}
} // end class
endif;
// EOL
<?php
//
// 例:
// wp-admin/admin-ajax.php?action=my_json&nonce=xxxxにアクセスするとjsonを出力する
//
$ajax = new WP_AdminAjax(
"my_json", // jsonを返すURLに使用されるパラメータ(半角英数)
"my_callback", // jsonを出力するためのコールバック関数
true, // trueを指定するとログインしてないユーザーでもアクセス可能になる
"my_nonce" // デフォルトでは第一引数と同じ値が使用される。
);
function my_callback() {
//
// いろいろな処理
//
return array('hoge' => 'fuga', 'foo' => 'bar');
}
// jsonを出力するためのURLを取得。jQuery.getJSON();などで使用するurlを取得できる。
$url = $ajax->get_url();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment