php-wordpressHow to make an AJAX request in WordPress using PHP?
Making an AJAX request in WordPress using PHP is relatively easy. The following example code block shows how to make an AJAX request in WordPress using PHP:
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
The output of the example code is:
10
Code explanation
-
add_action( 'wp_ajax_my_action', 'my_action_callback' );
- This line adds an action hook to WordPress which will trigger themy_action_callback
function when the AJAX request is made. -
function my_action_callback() {
- This line defines themy_action_callback
function which will be triggered when the AJAX request is made. -
global $wpdb;
- This line allows access to the WordPress database. -
$whatever = intval( $_POST['whatever'] );
- This line retrieves the value of thewhatever
parameter from the AJAX request. -
$whatever += 10;
- This line adds 10 to the value of thewhatever
parameter. -
echo $whatever;
- This line prints the value of thewhatever
parameter. -
wp_die();
- This line is required to terminate the AJAX request and return a proper response.
Helpful links
More of Php Wordpress
- How to get the current URL in WordPress using PHP?
- How to disable PHP warnings in WordPress?
- How to increase the upload limit in WordPress using PHP?
- How to check the PHP version in WordPress?
- How to run an SQL query in WordPress using PHP?
- How to create a snippet in WordPress using PHP?
- How to configure Nginx for WordPress?
- How to create a menu in WordPress using PHP?
- How to use get_header in WordPress using PHP?
- How to send an email using PHP in WordPress?
See more codes...