WordPress 插件:在管理面板中单击按钮调用函数 [英] WordPress Plugin: Call function on button click in admin panel

查看:28
本文介绍了WordPress 插件:在管理面板中单击按钮调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个 WordPress 插件,当单击管理面板中的按钮时调用 PHP 函数.我一直在查看编写基本 WordPress 插件和添加管理面板的教程,但我仍然不明白如何将按钮注册到插件中的特定功能.

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.

这是我目前所拥有的:

/*
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
} 


?>

推荐答案

好吧,您有两个选择.

1) 使用 AJAX 创建一个 admin-ajax 钩子,当用户单击按钮时,您将使用 JavaScript 执行该钩子.您可以在此处了解该方法:http://codex.wordpress.org/AJAX(确保添加随机数以确保安全( http://codex.wordpress.org/WordPress_Nonces )).这也是创建 admin-ajax 钩子的好资源:http://codex.wordpress.org/AJAX_in_Plugins

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) 将按钮放在一个表单中,将该表单发布到您的插件中并添加一些代码来处理 POST 表单(如果您这样做,请确保您包含一个随机数以确保安全( http://codex.wordpress.org/WordPress_Nonces ) 并确保尝试单击按钮的用户具有这样做的正确权限 http://codex.wordpress.org/Function_Reference/current_user_can

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

您尝试做的不是超级复杂,但它确实涉及对表单、PHP 和(也许)JavaScript 的良好理解.如果您的 JavaScript 没问题,我建议您使用选项 1,因为它不需要用户重新加载页面.

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.

这篇关于WordPress 插件:在管理面板中单击按钮调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆