When managing WordPress website, you have to know about different languages that help it function. Even if you don’t have to know about coding for creating website; you must know the languages. The one that helps these languages in creation is AJAX! Before we go to use AJAX with PHP, let’s know more about AJAX first. It is one of the technics of web developers that helps to develop interactive applications. With these applications your website could work smoother and faster. This will allow users to update content in website without reloading it. For working with AJAX you need to know other languages as well.
Some Things You Should Know About AJAX
AJAX in WordPress
In WordPress AJAX is used at a backend. Due to this when you make any changes into posts, moderate comments or make changes into categories the update will be instantly made. The AJAX is mostly used with JQuery in WordPress. WordPress uses AJAX in definite process!
After making the request it goes through ‘admin-ajax.php’ file in wp-admin folder. The requests would need a piece of data which is called ‘action’. It can be processed by using ‘get’ or ‘post’. This will prompt the code in ‘admin-ajax.php’ file to create hooks. The hooks are ‘wp_ajax_my_action’ and ‘wp_ajax_nopriv_my_action’. The phrase ‘my_action’ shows the value of variable ‘action’ of ‘get’ and ‘post’ method.
A WordPress AJAX Plugin
You can create a WordPress AJAX plugin by following these steps. If done carefully, it wouldn’t take more than few minutes. To start the process first you need to take an empty WordPress plugin created and activated in your website.
Then get a good name for this plugin. You can check if the plugin name is already taken by checking the plugin repositories.
Now you need to create a PHP file using this plugin name. The plugin should not share the PHP file. Your plugin will require users to put the PHP file in WordPress plugin directory. That’s why the plugin shouldn’t have common name or PHP file.
The WordPress can change the standard plugin directory. That’s why you should use ‘plugin_dir_path()’ and ‘plugin_url()dor’ path and URLs in PHP code.
We have successfully created WordPress AJAX plugin with PHP. Now we need to find the ‘single_php’ post template in the theme name. For this you need to go to the root directory of current website. This file should be open for edit.
Now we have created the required link successfully. This link will forward you to the ‘admin_ajax.php’ script. They can’t run any action in it yet. For creating the function in plugin file and to add it in hooks created on WordPress you need to insert a code.
By putting this code, when the user will click on ‘like this post’ the number of likes will be updated.
These are some ways to use AJAX with PHP in WordPress!