I need to create a WordPress plugin that calls a PHP function when a button in an admin panel is clicked. I’ve been looking at tutorials for writing basic WordPress plugins and adding admin panels but I still don’t understand how exactly to register a button to a specific function in my plug-in.
Here’s what I have so far:
/*
Plugin Name:
Plugin URI:
Description:
Author:
Version: 1.0
Author URI:
*/
add_action('admin_menu', 'wc_plugin_menu');
function wc_plugin_menu(){
add_management_page('Title', 'MenuTitle', 'manage_options', 'wc-admin-menu', 'wc_plugin_options');
}
function wc_plugin_options(){
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.') );
}
echo '<div class="wrap">';
echo '<button>Call Function!</button>'; //add some type of hook to call function
echo '</div>';
}
function button_function()
{
//do some stuff
}
?>
Although the answers on this page provided a useful start, it took a while for me to figure out how to get option (2) working. Given this, the following code might be of help to some people.
If you create a plugin with the following code and it will add a left hand menu option called ‘Test Button’ when you are in the admin area. Click on this and you will see a button. Clicking that button runs the
test_button_action
function. In my example function I’ve both put a message on the page and written to a log file.Well, you have two options.
1) Use AJAX to create an admin-ajax hook that you execute with JavaScript when the user clicks the button. You can learn about that approach here: http://codex.wordpress.org/AJAX (make sure to add a nonce for security ( http://codex.wordpress.org/WordPress_Nonces )). This is also a good resource for creating admin-ajax hooks: http://codex.wordpress.org/AJAX_in_Plugins
2) Put the button in a form, POST that form to your plugin and add some code to handle the POST’d form (if you do this, make sure you include a nonce for security ( http://codex.wordpress.org/WordPress_Nonces ) and also make sure that the user trying to click the button has the right privileges to do so http://codex.wordpress.org/Function_Reference/current_user_can
What you’re trying to do is not super-complex, but it does involve a good understanding of forms, PHP, and (maybe) JavaScript. If your JavaScript is ok, I’d recommend option 1, since it doesn’t require the user to reload the page.