duanmu2015 2016-01-04 17:15
浏览 111

如何在wordpress中制作自定义ajax处理程序?

i'm trying to make custom ajax handler in wordpress because the admin-ajax.php is taking to long to handle ajax requests from 7s to 10s so i google it and mange to do some custom ajax-handler.php like this

<?php
if (is_ajax_request()) {
    if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
        $action = $_POST["action"];
        switch($action) { //Switch case for value of action
            case "test": test_function(); break;
        }
    }
}

//Function to check if the request is an AJAX request
function is_ajax_request() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function()
{
    $response = wc_get_product(1463);
    header('Content-Type: application/json');
    echo json_encode($response);
    die();
}

and i send first the response as text $response = "test" and the ajax call was taking 300ms but when trying to call function from another file like $response = wc_get_product(1463); it throws an error in the response Fatal error: Call to undefined function wc_get_product() in C:\wamp\www\.... and i tried to make custom wordpress ajax handel using this ajaxflow plugin but it the seams thing so please please how can i call the functions from another files and many thanks in advance for any help.

  • 写回答

1条回答 默认 最新

  • dongquexi1990 2016-01-05 00:06
    关注

    You will need to load wp to use its functions

    require_once 'wp-load.php' //note find the file relative to your files location or do a dynamic url to find .. e.g. `$_SERVER['DOCUMENT_ROOT']`
    
    if (is_ajax_request()) {
        if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
            $action = $_POST["action"];
            switch($action) { //Switch case for value of action
                case "test": test_function(); break;
            }
        }
    }
    
    //Function to check if the request is an AJAX request
    function is_ajax_request() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
    
    function test_function()
    {
        $response = wc_get_product(1463);
        header('Content-Type: application/json');
        echo json_encode($response);
        die();
    }
    

    But wp-ajax itself is probably not the issue, did you test wp-ajax with simple output like 'test' ?

    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误