nbwphooks / wphooks
0.4.0
2021-05-17 15:59 UTC
README
一个用于创建简洁 WordPress AJAX 动作的简单类
Class ExampleAJAX extends WP_AJAX { protected $action = 'example'; protected function run(){ echo "Sucess!"; } } ExampleAJAX::listen(); // http://example.com/wp-admin/admin-ajax.php?action=example
简介: Medium 文章
功能
- 简单易用
- 完成后自动销毁
- 众多有用助手函数
安装
需要通过 composer 使用 WP_AJAX
$ composer require anthonybudd/wp_ajax
或者
下载 WP_AJAX 类并在 functions.php 文件的顶部引入它。
require 'src/WP_AJAX.php';
设置
您需要创建一个继承自 WP_AJAX 的新类。这个类必须有一个名为 $action 的受保护属性和一个名为 run() 的受保护方法。$action 将是 AJAX 动作名称 查看 wp_ajax_(action)。
Class Example extends WP_AJAX { protected $action = 'example'; protected function run(){ echo "Success!"; } }
监听
接下来,您必须调用静态方法 listen()。这将创建所有钩子,以便 WordPress 在正确触碰到 AJAX 端点时调用 run() 方法。注意:您必须为每个 AJAX 动作调用 listen() 方法。
ExampleAJAX::listen();
如果您希望仅允许已登录用户访问您的 AJAX 端点,请将 FALSE 作为参数传递给 listen 方法。
ExampleAJAX::listen(FALSE);
JSON 响应
如果您想使用数据响应 AJAX 请求,JSONResponse() 方法将自动设置内容类型头为 'application/json' 并将提供的数据编码为 JSON。
我知道 WordPress 有一个名为 wp_send_json() 的函数,但由于我知道这会让 WP 开发者感到烦恼,因此我不会移除它。
Class ExampleAJAX extends WP_AJAX{ .. protected function run(){ $post5 = get_post(5); $this->JSONResponse($post5); } }
助手方法
Example::url() // Returns the url of the ajax endpoint. Example http://ajax.local/wp/wp-admin/admin-ajax.php?action=example $this->isLoggedIn(); // Returns TRUE or FALSE if the current visitor is a logged in user. $this->has($key); // has() will return TRUE or FALSE if an element exists in the $_REQUEST array with a key of $key $this->get($key, [ $default = NULL ]); // The get() method will return the specified HTTP request variable. If the variable does not exist it will return NULL by default. If you would like to set a custom string as the default, provide it as the second argument. $this->requestType(); // Returns 'PUT', 'POST', 'GET', 'DELETE' depending on HTTP request type $this->requestType('POST'); // Returns (bool) $this->requestType(['POST', 'PUT']); // Returns (bool)
示例
Class CreatePost extends WP_AJAX { protected $action = 'create_post'; protected function run(){ if($this->isLoggedIn()){ $post = [ 'post_status' => 'publish' ]; if( $this->requestType(['POST', 'put']) ){ $post['post_content'] = 'This request was either POST or PUT'; }else if( $this->requestType('get') ){ $post['post_content'] = 'This request was GET'; } $post['post_title'] = sprintf('This post was created by %s', $this->user->data->user_nicename); wp_insert_post($post); $this->JSONResponse($post); } } } CreatePost::listen(); // http://example.com/wp-admin/admin-ajax.php?action=create_post