anthonybudd/wp_ajax

此软件包最新版本(v1.0.3)没有提供许可证信息。

v1.0.3 2017-11-29 12:25 UTC

This package is auto-updated.

Last update: 2024-09-09 13:50:51 UTC


README

WordPress 简单控制器

WP_AJAX 是一个用于与 WordPress 内置 AJAX 系统交互的类。这个类旨在完全抽象开发者从基于钩子的传统系统到干净的控制器式结构。只需定义一个类,使用 url($params = []) 方法输出 URL,然后在 run() 方法中编写您想执行的代码。

简介: Medium 文章

Class ExampleAction extends WP_AJAX{

    protected $action = 'example-action';

    protected function run(){

    	// Your Code Here!
    	
    	update_option('name', $this->get('name'));

    }
}
ExampleAction::listen();

ExampleAction::url() // http://example.com/wp-admin/admin-ajax.php?action=example-action
ExampleAction::url(['name' => 'Anthony Budd']) // http://example.com/wp-admin/admin-ajax.php?action=example-action&name=Anthony%20Budd

ExampleAction.php

前端

<a href="<?= ExampleAction::url(['name' => 'Anthony Budd']) ?>" >This is a link</a>

Page-Template.php

$('.submit-btn').click(function(){

    $.post('http://example.com/wp-admin/admin-ajax.php',{
        action: 'example-action',
        name: $('.name-field').val(),
    },function(data){
        console.log(data)
    }, 'JSON');
    
});

script.js

安装

使用 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 端点,请在 listen() 方法中添加参数 FALSE。

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