最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rest api - Ways to load admin-ajax faster without initializing all plugins?

programmeradmin5浏览0评论

I'm facing a problem with wp ajax performance. I'm initializing an ajax call from my javascript side but the response takes 3-5 secs to come back. I understand that admin ajax call has to load the whole wp core and that would definitely be a performance hit for us.

Is there a way to still use the admin ajax call, but without loading all plugins? Essentially in my php api, I'm only using some values from wp-config. Or is there any better ajax suggestions given my use case? Is it possible to use regular rest API(without going through admin-ajax) but could still use the values from wp-config?

Here is my js code(ajax.js):

jQuery.ajax({
        url: ajax_object.ajax_url,
        data: {
            action: 'geo_ip_api'
       },

        type: 'POST',
        success: function (output) {
            console.log(output);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(xhr.responseText);
            console.log(thrownError);
        }
    });

Here is my php api(api.php):

function geo_ip_api(){
global $bannerRequiredRegions;
global $ipBlackList;
$isInEU = 'null';
$ipAddress = get_ip_address();
if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList)))
{
    try
    {
        require_once 'HTTP/Request2.php';
        /* retrieving values from wp-config */
        $api_url = GEO_API_URL;


        $request = new Http_Request2($api_url);
        $url = $request->getUrl();

        //sending HTTP request logic here. No dependency on wordpress
    }
    catch (Exception $ex)
    {
        //TODO: put log here
    }
}

echo $isInEU;

}

Any help appreciated! Thanks in advance. I've searched lots of post and none of those could answer my question.

I'm facing a problem with wp ajax performance. I'm initializing an ajax call from my javascript side but the response takes 3-5 secs to come back. I understand that admin ajax call has to load the whole wp core and that would definitely be a performance hit for us.

Is there a way to still use the admin ajax call, but without loading all plugins? Essentially in my php api, I'm only using some values from wp-config. Or is there any better ajax suggestions given my use case? Is it possible to use regular rest API(without going through admin-ajax) but could still use the values from wp-config?

Here is my js code(ajax.js):

jQuery.ajax({
        url: ajax_object.ajax_url,
        data: {
            action: 'geo_ip_api'
       },

        type: 'POST',
        success: function (output) {
            console.log(output);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(xhr.responseText);
            console.log(thrownError);
        }
    });

Here is my php api(api.php):

function geo_ip_api(){
global $bannerRequiredRegions;
global $ipBlackList;
$isInEU = 'null';
$ipAddress = get_ip_address();
if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList)))
{
    try
    {
        require_once 'HTTP/Request2.php';
        /* retrieving values from wp-config */
        $api_url = GEO_API_URL;


        $request = new Http_Request2($api_url);
        $url = $request->getUrl();

        //sending HTTP request logic here. No dependency on wordpress
    }
    catch (Exception $ex)
    {
        //TODO: put log here
    }
}

echo $isInEU;

}

Any help appreciated! Thanks in advance. I've searched lots of post and none of those could answer my question.

Share Improve this question asked Nov 1, 2017 at 5:41 brandNewWPUserbrandNewWPUser 11 silver badge1 bronze badge 1
  • you are doing an http request in your ajax handler, there is no way you will get a fast response – Mark Kaplun Commented Nov 1, 2017 at 6:09
Add a comment  | 

2 Answers 2

Reset to default 1

If your requests take 3-5 sec to finish, then there is most likely something else going on. The admin Ajax itself won't take that much to load. You might be having some heavy plugin, or having some hooks running expensive meta queries on load.

You can try the REST-API, which is slightly faster than Admin-Ajax. But the response will be in JSON, instead of plain HTML, you have to note that one.

Also, there might be an issue with the TTFB. Try disabling all the plugins, revert to default theme (move your code to default theme) and check if the problem still persists.

This might or might not work best for you, custom endpoints are generally useful for Polling and other sort of situations and not for regular ajax work. You might rather look into other methods like caching the results from your API.

Also from my discussion with Mark, I do agree that using this in a public plugin is not a very good idea as it requires a lot of changes on user end, and rather this is something to be used if you're building a solution specific to a site.

For the sake of information I'm adding the alternates to WP Ajax.

You can make use of WordPress constant SHORTINIT if you don't want to load the plugins. It might not help in making ajax request faster in this particular case since you're making a HTTP request as Mark mentioned in comments.

If SHORTINIT is set to true, WordPress doesn't loads most of the thing for a Ajax request, just the bare minimum.

And if you need to use any of other features, you can just load the required files from WordPress.

Here is a very nice article to help you get started, and there are 3 differnt approaches in here: https://deliciousbrains/wordpress-rest-api-vs-custom-request-handlers/

I'll just post a excerpt from the article for the use case of SHORTINIT. You need to create a PHP file in your theme or plugin that starts out with this code and add you handler for the rest of processing.

// Set SHORTINIT to true
define( 'SHORTINIT', true );

// get the path for wp-load.php, considering this file in root directory of plugin/theme
$wp_root_path = dirname( dirname( dirname( __FILE__ ) ) );
// Load wp-load.php file (which loads wp-config.php and bootstraps WordPress)
require( $wp_root_path . '/wp-load.php' );

// $wpdb class for any query you might need
global $wpdb;

// Do your PHP code for rapid AJAX calls with WP!
function geo_ip_api(){
 global $bannerRequiredRegions;
 global $ipBlackList;
 $isInEU = 'null';
 $ipAddress = get_ip_address();
 if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList))) {
   try {
    require_once 'HTTP/Request2.php';
    /* retrieving values from wp-config */
    $api_url = GEO_API_URL;


    $request = new Http_Request2($api_url);
    $url = $request->getUrl();

    //sending HTTP request logic here. No dependency on wordpress
  }
   catch (Exception $ex){
    //TODO: put log here
   }
 }

 echo $isInEU;
}
发布评论

评论列表(0)

  1. 暂无评论