Using Ajax on Admin Page in WordPress Plugins

Today, I'm writing a rather simple WordPress Ajax example that demonstrates how to user Ajax in a wp-admin page from a WordPress Plugin.

Using Ajax in wp-admin is a little easier than using it on the front-end of a WordPress site because of the ajaxurl JavaScript global variable which refers to the admin-ajax.php url.

In the following code example the goal is to provide an admin page with a delete post link that is powered by Ajax. Therefore the code enables the deletion of a WordPress post without the obtrusive page refresh!

This is a pretty bare-bones example meant as a learning tool. It could be fleshed out much more to be more practical, but I wanted to keep it simple to get the main point across, which is how to do a simple Ajax request from wp-admin.

The Essential Code

First, for those of you that only need to see the basics, I'll demonstrate the essential code for the Ajax to work. Further down this page, I'll put it all together in a simple plugin for those of you that may need to see a working example to grasp the concept better. Here is the essential code to enable an Ajax delete post button:

First, a simple HTML line to call our JavaScript function onclick:

<span onclick='ajax_delete_posts(<?php echo $ID; ?>)' style='color:red;cursor:pointer' title='Delete Person!'>X</span> <?php echo $title; ?><br />

In the above, you'll notice the ajax_delete_posts JavaScript function is called. ajax_delete_posts is the function we must create! Of course you'll need to define the post id in $ID and the post tile in $title using PHP, but this is just to show you how I intend to call the Ajax/JavaScript function

Second, we use PHP to generate our ajax_delete_posts function in JavaScript code:

You can rename the ajax_delete_posts as you wish, just make sure to rename it in your HTML above too if you do. Here's the code to generate the JavaScript from within your PHP file, the plugin's main file normally:

<?php

//add Ajax for deleting posts or custom post type(replace 'post' with cpt name):
add_action('admin_footer', 'del_posts_js');
function del_posts_js() {
?>
    <script type="text/javascript" >
    function ajax_delete_posts(t) {

        var data = {
            'action': 'del_posts_with_ajax',
            't': t
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            alert('Ajax server response: ' + response);
        });
    }//end Ian's JS AJAX function
    </script>
<?php
}

?>

Notice in the above code how we pass the post id to the JavaScript function using the "t" variable. Also it's important to note your data variable's action value as you will need to use the same value for the function name in the below code. Feel free to use whatever text you want for the action as long as it can be an appropriate PHP function name in the code below as well.

Finally, the third step is to add your PHP function named after the action named above and also hook into it with "wp_ajax_" followed by the action named above as well, so in our case the hook we use would be "wp_ajax_del_posts_with_ajax". However, if you use a different action, such as "do_aj" for example, then your action hook would read "wp_ajax_do_aj". Got it? I hope so, but the code example should help too, so here it is:

<?php
add_action( 'wp_ajax_del_posts_with_ajax', 'del_posts_with_ajax' );

function del_posts_with_ajax() {

    $tpidof = $_POST['t'];
    
    if(wp_trash_post($tpidof)){
        echo $tpidof." Deleted!";
    }else{
        echo "$tpidof Failed to delete!";
    }

    wp_die(); //required to terminate immediately and return response!
}
?>

In the above code example, we first set up our action hook by using the hook "wp_ajax_" followed by the action we used in the "var data" line further above.  Then we write a PHP function named exactly like the action we used above and be sure to also name the function as the parameter in the action hook as well and you will be good to go!

Putting it all together in a simple Ajax WordPress Plugin

Next I'll show you the example plugin I created to demonstrate exactly how this all works together in case some of you failed to grasp it from my previous explanations. You can cut and paste the following PHP code into a file named "ajax_post_delete.php" and place it on your desktop in a folder named "ajax_post_delete" and I promise you the code will function on any standard WordPress installation as of the day I wrote this. Here is the complete "Ajax Post Delete" WordPress plugin code in a single file example plugin:

<?php
/*
Plugin Name: Ajax Post Delete
Plugin URI: http://jafty.com/ajax_post_delete

Description: A plugin used in the article at http://jafty.com/blog/?p=10739 in order to demo an admin ajax example

Author: Ian L. of Jafty.com
Author URI: http://jafty.com

Version: 1.0.0

License: GNU General Public License v2.0
License URI: http://www.opensource.org/licenses/gpl-license.php
*/

//function to add wp-admin menu:
add_action('admin_menu', 'add_ajax_post_delte_admin_menu');
function add_ajax_post_delte_admin_menu() {

    $page_title='Delete posts';
    $menu_title='Delete posts';
    $capability='manage_options';
    $menu_slug='del_posts_pg';
    $function='mk_dele_pg';
    $icon_url = '';
    $position='4';
    
    add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);
    

}//------------end add_ajax_post_delte_admin_menu function------------------

function mk_dele_pg(){
?>
<h1>Delete posts</h1>
<?php
//get all posts:
$args = array(
'post_type' => 'post',
'posts_per_page'=>-1
);
global $wp_query;
$wp_query = new WP_Query($args);
//start looping posts
while($wp_query->have_posts()) : $wp_query->the_post();
$person = get_the_title();
$personID = get_the_ID();
//echo $person."<br />";
echo "<span onclick='ajax_delete_posts($personID)' style='color:red;cursor:pointer' title='Delete Person!'>X</span> $person<br />";
endwhile;

}//end mk_dele_pg function

//add ajax for deleting touchpoint history for posts CPT:
add_action('admin_footer', 'del_posts_js'); // Write our JS below here

function del_posts_js() {
?>
    <script type="text/javascript" >
    function ajax_delete_posts(t) {

        var data = {
            'action': 'del_posts_with_ajax',
            't': t
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            alert('Ajax server response: ' + response);
        });
    }//end Ian's JS AJAX function
    </script>
<?php
}

add_action( 'wp_ajax_del_posts_with_ajax', 'del_posts_with_ajax' );

function del_posts_with_ajax() {

    $tpidof = $_POST['t'];
    
    if(wp_trash_post($tpidof)){
        echo $tpidof." Deleted!";
    }else{
        echo "$tpidof Failed to delete!";
    }

    wp_die(); //required to terminate immediately and return response!
}

?>

That's it! copy and paste the above code into your .php file and you've got a simple WordPress plugin that will demonstrate the use of Ajax effectively in a custom admin page of your WordPress website. Feel free to modify the code as needed, but please change the plugin name if you intend to distribute it. Thank you and Good Luck!

Leave a Reply

Your email address will not be published. Required fields are marked *