Admin ajax php takes a long time to load. How to reduce server load using admin-ajax in WordPress. Disabling Heartbeat API completely

For better SEO and user experience, experts always recommend for the end user. In this context, if a lot of users visit your site, the WordPress dashboard can be slow to respond.

While testing the speed of your WordPress site using online speed testing tools, you may have noticed that the file admin-ajax.php responsible for the slow loading experience. In this article, we'll walk you through this file and how you can reduce server response times and CPU usage by reducing the number of requests generated by admin-ajax.php.

What is admin-ajax.php in WordPress?

Back in 2013, WordPress introduced the WordPress Heartbeat API, which provided several important features, such as an autosave function, upon expiration of a lock warning login while another user is writing or editing a WordPress post.

Two very salient features of the Heartbeat API:

1. Autosave

Whenever you save a post project and continue working on it, WordPress will automatically save the post additions. There is a clear distinction between autosaving and manually saving a project. Check out the following screenshot, which shows both types of saves:

2. Blocking message

Whenever you try to edit a post that another user is working on, a pop-up warning about the situation will appear. There are three actions available to you.

The above features are made possible by the WordPress Heartbeat API, which creates a connection between the server and the browser for the corresponding message and responses.

WordPress Heartbeat API generates requests for communication with the server and triggers events for receiving / responding data. Typically, this increases the load on the server and ultimately slows down the WordPress admin panel.

Live example

We entered the WordPress dashboard and started editing the post. Next, we left the tab open for a few minutes and started browsing the other tabs. The dashboard is still in the system and you can see that admin-ajaxsends requests continuously.

According to the ticket mentioned above, admin-ajax.php in WordPress generates requests every 15 seconds. Any connection with the server can be a request.

Speed ​​up your WordPress admin panel

To speed up the WordPress backend, the best approach is to disable the Heartbeat API, or at least set a longer amount of time so that it doesn't generate requests to the server every few seconds.

Install the Heartbeat Control plugin

Login to your WordPress admin area and go to Plugins >> Add New, find Heartbeat control, install and activate his.

Go to the tab Settings >> Control Heartbeat Settings... There you will find three drop-down menus for configuring the plugin.

You can choose the area where the Heartbeat API will work. There are three options to choose from:

  • WordPress Dashboard: This will enable the Heartbeat API in the WordPress dashboard.
  • Frontend: This will enable the API in the web interface.
  • Post editor: Check this box if you want to allow Heartbeat API to turn on autosave and block mail functions.

Select this option if you want the WordPress Heartbeat API to be disabled in specific locations. Be careful when choosing a location because other plugins may also use the WordPress Heartbeat API. If you are the only WordPress backend user I would suggest disabling it everywhere and then checking if it breaks the website. However, if your site has more than one user who contributes regularly, we would suggest that you only allow the Heartbeat API on the post edit pages.


This dropdown menu allows you to set the time interval, between 0 - 300 seconds, for administering Ajax requests. If you set it to 120 seconds, then a request will be generated every 120 seconds. This will significantly reduce the load on the server. Customize it according to your needs.

Creating multiple rules

You can create multiple rules based on your requirements. For example, you want WordPress to call every 120 seconds, but after editing, fire for 60 seconds. To do this, you need to create two rules. One for the WordPress dashboard and another for the post editor and set their frequency to 120 and 60 respectively.

Now that you have everything configured, it's time to check which plugins are slowing down your website using the admin-ajax.php file.

Go to GTmetrix, enter your site url. It will take a few minutes to analyze the site. After that go to the Waterfall tab and you will see how long the file takes for connections and responses. Scroll down a bit and see if there is an entry POST admin-ajax.php... If so, expand it and go to the Post tab. You can identify the culprit here. In our case, the "desktop switch" plugin uses the admin-ajax.php file and continually sends requests to the server. It's time to decide whether to replace it with another plugin or remove it.

Final Words

Given its feature set, the Heartbeat API is very useful on your WordPress site. However, if not used correctly, it can increase load times on the WordPress backend and on the site itself by sending queries to and fro in WordPress.

There are only two solutions to this problem. Or disable Heartbeat API / enable it only in a few places.

If you are using any caching plugin like W3TC, remember to disable the object cache. It will also speed up your WordPress dashboard.

If you have any suggestions or request, feel free to leave a comment below.

V technical support the site is often asked questions related to the work of the admin-ajax.php script on the hosting (often its work is interrupted, ends with an error, or causes a heavy load on the hosting). How to solve all these problems?

What is admin-ajax.php

The admin-ajax.php script (the so-called WordPress heatbeat, included since WordPress 3.5.2) performs the extension of the WordPress user session - for the convenience of using the admin panel. If the administrator or editor often works with the site, then this eliminates the need to enter a username / password each time. But for 99% of site visitors, this functionality is most likely not needed: after all, they only read the content, do not edit it.

In some cases, admin-ajax.php can be responsible for increased memory and CPU consumption on hosting: due to frequent - every 15 seconds - calls to the database against the background of other requests (most of which can already be cached). Since the admin-ajax.php functionality is dynamic (it cannot be cached), the Airee cloud, like any other caching tool, passes all requests directly to the server, creating a significant load.

How to deal with admin-ajax.php

The best way to remove the load from admin-ajax.php is to completely disable this functionality. This is best done either by editing within the WordPress engine or by installing the appropriate plugin.

To disable WordPress Heartbeat for all pages except the new post page, you need to add to your theme's header.php:

add_action ("init", "my_deregister_heartbeat", 1); function my_deregister_heartbeat () (global $ pagenow; if ("post.php"! = $ pagenow && "post-new.php"! = $ pagenow) wp_deregister_script ("heartbeat");)

To solve this problem through WordPress plugins you can use

How can I upload any files like images to the server using AJAX and jQuery? This is done quite simply! And below we will analyze everything in detail.

In those "ancient" times, when there was no jQuery yet, or maybe it was, but browsers were not so sophisticated, uploading a file to a site using AJAX was a dreary affair: through all sorts of crutches like iframe. I did not find those times, and who is interested in it now. And now another thing is interesting - that saving files to the site is very simple. Even without experience and understanding of how AJAX works, a webmaster can quickly figure out which way. And this article will help him. If you reinforce these capabilities with WordPress functions, then securely processing and uploading files to the server becomes completely trivial and even interesting (for an example with WordPress, see the end of the article).

However, no matter how simple everything is, it should be noted that the minimum experience with files and basic knowledge of Javascript, jQuery and PHP are still required! At the very least, you need to understand how files are uploaded to the server, how AJAX works in general terms, and at least a little you need to be able to read and understand the code.

The method described below is quite stable, and in fact relies on the Javascript object new FormData (), which is basicly supported in all browsers.

For a clearer perception of the material, it is divided into steps. That's all, let's fly ...

AJAX File Uploads: A Generic Example

It all starts with the presence on the site of the input field of type file. It is not necessary for this field to be part of the form (tag

).

Thus, we have HTML code with a file field and a button "Upload files".

download files

Step 1. Data from the file field

The first step is to get the data of the downloaded files.

When you click on the file-field, a window for selecting files appears, after selection, the data about them is stored in the input field, and we need to "pick up" them from there. To do this, we will hang on the change JS event a function that will save the existing file-field data to the JS variable files:

Var files; // variable. will contain file data // fill the variable with data when the value of the file field changes $ ("input"). on ("change", function () (files = this.files;));

Step 2. Create an AJAX request (on click)

We have the file data, now we need to send it via AJAX. We hang this event on a click on the "Upload files" button.

At the moment of clicking, create a new object new formData () and add data from the files variable to it. With formData () we will make the submitted data look as if we were just submitting the form in the browser.

For such a request to take place, jQuery needs to specify additional AJAX parameters, so the usual $ .post () function is not suitable and we use a more flexible analogue: $ .ajax ().

Two important additional parameters need to be set to false:

ProcessData Disables processing of transmitted data. By default, for example, for GET requests, jQuery collects the data into a query string and appends that string to the end of the URL. For POST data, it does other transformations. Any changes to the original data will interfere with us, so we disable this option ... contentType Disables setting the request type header. The default jQuery setting is "application / x-www-form-urlencoded. This header will not send files. If you set this parameter to" multipart / form-data ", PHP will still not be able to recognize the transmitted data and will display the warning" Missing boundary in multipart / form-data "... In general, the easiest way is to disable this option, then everything works! // processing and sending an AJAX request when the button is clicked upload_files $ (". upload_files "). on (" click ", function ( event) (event.stopPropagation (); // stop all current JS events event.preventDefault (); // stop the default event for the current element - click for tag // do nothing if files is empty if (typeof files == "undefined") return; // create a form data object var data = new FormData (); // fill the data object with files in a format suitable for sending $ .each (files, function (key, value) (data.append (key, value);)); // add a variable to identify the request data.append ("my_file_upload", 1); // AJAX request $ .ajax ((url: "./submit.php", type: "POST", // important! Data: data, cache: false, dataType: "json", // disable processing of transmitted data, let it be passed as is processData: false, // disable setting the request type header.This is how jQuery will tell the server that this is a string request contentType: false, // function for a successful server response success: function (respond, status, jqXHR) (// OK - files loaded if (typeof respond.error === "undefined") (// output the paths of uploaded files to the ".ajax-reply" block var files_path = respond.files; var html = ""; $ .each (files_path, function ( key, val) (html + = val + "
";)) $ (". ajax-reply "). html (html);) // error else (console.log (" ERROR: "+ respond.error);)), // server response error function error: function (jqXHR, status, errorThrown) (console.log ("ERROR AJAX request:" + status, jqXHR);)));));

Step 3. We process the request: upload files to the server

Now the last step: you need to process the submitted request.

To visually process the request without additional checks for files, i.e. just save the received files to the desired folder. Although, for safety, the sent files must be checked, at least the extension (type) of the file ...

Let's create a file submit.php with the following code (it is assumed that submit.php is in the same folder as the file from which the AJAX request is sent):

$ done_files): array ("error" => "Error loading files."); die (json_encode ($ data)); )

That's all!

Important! This code only shows how to get and save files. In fact, you need to check the formats of the received files, their size, transliterate the Cyrillic names and possibly do some other checks.

In order not to collect the above download code in parts, I suggest downloading it.

Copy the contents of the archive to your php server, go to the main pack (in the browser) and try to upload the files. So, you will see "live" what and how it works.

AJAX File Uploads: An Example for WordPress

For WordPress, handling an AJAX request is many times easier, because there are ready-made functions, for example, media_handle_upload ().

The first and second steps are similar, but in the third step we will use a built-in function that will add a file to the library and link it to the current post.

For the code below to work, you need to add it to your theme's functions.php file. Next, create a page with ajax_file_upload shortcut and go to this page. In the content, you will see a form to add a file. Select files and check if everything has loaded ...

This is a complete example of how to securely upload files to your server in a WordPress environment.

post_name! == "ajax_file_upload") return $ text; return $ text. = "

";) // JS code function ajax_file_upload_jscode () (?> $ max_size || $ sizedata / * height * /> $ max_size) wp_send_json_error (__ ("The picture cannot be larger than". $ max_size. "px in width or height ...", "km")); // handle loading the file require_once ABSPATH. "wp-admin / includes / image.php"; require_once ABSPATH. "wp-admin / includes / file.php"; require_once ABSPATH. "wp-admin / includes / media.php"; // filter of allowed file types - only images are allowed add_filter ("upload_mimes", function ($ mimes) (return ["jpg | jpeg | jpe" => "image / jpeg", "gif" => "image / gif", "png" => "image / png",];)); $ uploaded_imgs = array (); foreach ($ _ FILES as $ file_id => $ data) ($ attach_id = media_handle_upload ($ file_id, $ post_id); // error if (is_wp_error ($ attach_id)) $ uploaded_imgs = "Error uploading file` ". $ data [" name "]." `:". $ attach_id-> get_error_message (); else $ uploaded_imgs = wp_get_attachment_url ($ attach_id);) wp_send_json_success ($ uploaded_imgs); )

Hello everyone. Continuing the topic of speeding up a website on wordpress. In this article, we have removed unnecessary things from the files, but there is more to come. In general, wordpress themes are good, which makes it possible to change the code the way you want, for different desires.

When you buy hosting, then, of course, you estimate how much memory you need for the site and what load it will have. And, if you are on a limited budget, then you would need to save on these parameters.

There is such a mechanism in the engine - HeartBeat API... Why is it needed? What it is?

HeartBeat API is responsible for

  • for autosave;
  • for blocking a page or post for all other site administrators while you are editing something there;
  • for updating the user's presence information in the console.

You understand, I hope that at this moment there is simply a devouring of resources, because there are constant requests for hosting to the admin-ajax.php file. And if you like to open several admin panel tabs at once, then this is generally awesome. Forgive me for the jargon. Something requests are sent offline for each tab.

Essentially, The HeartBeat API is the most resource-intensive engine ever in the WordPress engine..

Do you need such a mechanism? Of course, everyone decides for himself. I don’t need it.

It is considered that it makes sense to disable it, you are the only administrator, and also, if your account has enough resources, but while the administrator is in the console, the loads increase, and significantly.

According to my observations, after turning off HeartBeat API, the occupied volume of my site has decreased almost 2.5 times! I'm serious. It's a pity I didn't make a screen, but I don't want to go back to its original state.

How to speed up a wordpress site by disabling the HeartBeat API

Disconnection HeartBeat API code

Everything is very simple. It should be added to the beginning of the functions.php file, immediately after the tag

Add_action ("init", "stop_heartbeat", 1); function stop_heartbeat () (wp_deregister_script ("heartbeat");)

And you will be happy.

Attention! This code may not match your site. It all depends on the installed theme, plugins and settings. You can try and if the code is incompatible with some element of the site or something breaks down and does not work at all, you can always return everything back. Just erase the code.

HeartBeat Control Plugin

Don't be friends with codes and are you afraid to harm your site? There is such a solution for you.

Install the HeartBeat Control plugin (select plugins in the console, install a new one, look for a plugin in the search, install and activate).

Go to the settings (in the Console Tools -> HeartBeat Control). In the settings, you can select the following parameters:

1. Disable or not HeartBeat for the entire site or use it for some sections.

2. You can and should edit the frequency of requests to the admin-ajax.php file. When installed, it is indicated, most likely, 15 seconds. If you change, say, to 30 seconds, then the resource consumption will decrease by 25% for these requests at once! And if you increase the time even more, then even more. Impressive, huh?

Attention!

  • Disabling the HeartBeat API disables the autosave feature. Occasionally, do save pages and notes as you edit them (as needed).
  • Disabling HeartBeat API happens in a specific template. If you change the template, then everything must be done again.
  • If you have updated the current theme, then after the update, the disconnection must be repeated.

Good luck to all!

2016-05-05T09: 48: 44 + 00: 00 Hope WordPress how to speed up wordpress

Hello everyone. Continuing the topic of speeding up a website on wordpress. In the article How to speed up wordpress by minifying CSS, HTML and Javascript, we removed the unnecessary from the files, but there is more to come. In general, wordpress themes are good, which makes it possible to change the code the way you want, for different desires. When you buy hosting, then of course you are considering ...

Nadezhda Trofimova [email protected] Administrator Blog Site

You may also be interested in:

How to make a favicon for a website

A favicon is a beautiful icon that everyone sees next to the name of the site in the browser. Favicon allows the site to stand out, both in browser bookmarks and in ...

Beautiful buttons for the site

Good day to all. Suddenly there are those who want to place beautiful buttons on their website, but they cannot find it. In fact, in search engines, I tried ...

Example 404 page

Hello dear reader of my blog. This article is about absolutely nothing, just finally got around to a 404 page.

How and where the Title and Description tags are registered

What are Title and Description tags? These tags are required to optimize your website. If the tags are incorrectly spelled out, search engines will not index your article. Many...

The stream of useful advices to users of the world's most popular free CMS will never run out. Precisely because it is popular and because it has features that are important to remember. Earlier we talked about how:

Today we will slightly expand the second theme and disable a very resource-intensive and not everyone needs WordPress mechanism called HeartBeat API.

HeartBeat API- WordPress functionality that provides things like:

  • Autosave;
  • Blocking a post or page for other site editors while the post or page is being edited by one person;
  • Updating information that the user is still in the administrative part (console).

It does this by maintaining communication between your browser (where you edit the site) and the server (where the site is stored).

In fact, this is expressed in constant requests with an interval of 15-30 seconds (depending on the installed version) to one specific admin-ajax.php file from almost any page of the admin panel. The situation is aggravated if you prefer to keep multiple console tabs open at once: requests are sent autonomously from each tab. In fact, HeartBeat API is the most resource intensive of all standard WordPress mechanisms..

We will disable this function today. It is recommended to disable the HeartBeat API for your WordPress site if:

  • In general, your sites have enough resources on your account, significant excess occurs only while working in the console;
  • The site is edited only by you personally(that is, the site has 1 editor, not several).

Attention! This solution is not suitable for all sites. It depends on the theme installed on the site, plugins and individual site settings. You can try it, and if it turns out to be incompatible with any of the site elements or affects an important site function for you, you can always enable HeartBeat API by returning the previous settings.

How to disable HeartBeat API

To do this, you need to make changes to the file functions.php inside the folder with the current active theme (template) of the site. This can be done in the file manager or via FTP.

The path to the functions.php file looks like this: / path_to_site_root/wp-content/themes/theme_name/functions.php.

Add at the very beginning of the file after the tag

Add_action ("init", "stop_heartbeat", 1); function stop_heartbeat () (wp_deregister_script ("heartbeat");)

These lines disable HeartBeat for the entire site.

HeartBeat Control Plugin

There is also a less radical solution than completely disabling the HeartBeat API. It is provided by a special plugin Heartbeat control... Install it, activate it and go to the settings ("Tools" -> "HeartBeat Control"). In the settings, you can choose the following parameters:

1. Whether to disable HeartBeat for the entire site or allow its use only for its individual sections, for example, for the page for editing and publishing records in the administrative panel.

2. Frequency of requests to the admin-ajax.php file. By default, it can be 15 seconds - change this value, for example, to 60 seconds, and thus reduce resource consumption for these queries by as much as 75%!

What is important to remember

  • By disabling the HeartBeat API, we disabled the autosave feature. Save the edited pages and notes periodically (as needed).
  • Since the HeartBeat API is disabled at the site theme (template) level, as soon as you change the theme (template) of the design, the HeartBeat API will work again. The deactivation procedure will need to be repeated for each new theme that you start using on the site.
  • The same applies to updating the current theme: after the update, the disconnection procedure must be repeated.

We wish you pleasant work!