我正在开发一个简单的WordPress插件,管理员可以使用管理表单创建用户角色。如果角色已经存在,我希望显示一个admin_notice。
我的问题是,甚至角色存在,信息没有出现。如果我正确理解,这是因为表单实际上是被重定向到admin-post.php的。如果是的话,提交后如何显示admin_notice?
简言之,我有以下几点:
检查和显示admin_notice的代码片段
<?php
function save_user_role()
{
$role_name = $_POST['role_name'];
$role_slug = sanitize_title_with_dashes($role_name);
$role = get_role($role_slug);
if (!empty($role))
{
$notice = 'Role exists';
do_action('admin_notices', $this->display_notice($notice));
// return; // If I use the return the correct message coming up in a blank page.
}
else
{
// Save the role
}
}下面是我编写的完整代码
function save_user_role() {
// Role already exists?
$role_name = $_POST[ 'coolmedia_role_name' ];
$role_slug = sanitize_title_with_dashes( $role_name );
$role = get_role( $role_slug );
if( ! empty( $role ) ) {
// Error. Role already exists
$notice = 'Speficed role ' . $role_name . ' already exists';
do_action( 'admin_notices', $this->display_notice( $notice ) );
} else {
// Safe to create the new role
$role_caps = array(
'read' => true,
);
...
add_role( $role_slug, esc_html( $role_name ), $role_caps );
// Redirect back to form page
wp_redirect( admin_url( 'admin.php?page=user-roles' ) );
}
}显示通知功能:
function add_user_role_markup() { ?>
<div class="wrap">
<h1>Add Role</h1>
<form method="post" action="<?php esc_html(admin_url('admin-post.php')); ?>">
<table class="form-table">
<tr class="first">
<th>Role name</th>
<td><input required type="text" id="role_name" name="role_name" /></td>
</tr>
<tr>
<th>
<?php
('coolmedia-role-save', 'coolmedia-role-nonce'); ?>
<input type="hidden" name="action" value="new_user_role">
</th>
<td><?php
('Save Role'); ?></td>
</tr>
</table>
</form>
</div>
<?php
}发布于 2018-02-22 13:03:12
这取决于何时调用save_user_role以及该函数之后还会发生什么。admin_notices钩子可能正在运行,但是(正如您所建议的)发生了重定向,这将导致它在重定向之后不开火,因为(正确地说) save_user_role不再被调用,或者save_user_role在调用admin_notices钩子之后启动(在这种情况下,您已经太晚了)。
一种解决方案可能是在数据库中临时存储一个选项和通知,然后检查该选项并根据需要显示它。这样,WordPress就可以重定向,然后在返回时检查并显示您的通知。
就像这样。(注意:我的add_action假设这种情况发生在一个类中,我认为这是您如何根据对$this->display_notice()的使用构造它的)
function save_user_role(){
...
if( ! empty( $role ) ) {
// Error. Role already exists
$notice = 'Specified role ' . $role_name . ' already exists';
update_option( 'coolmedia_role_exists_message', $notice, 'no' );
}
...
}
add_action( 'admin_notices', array( $this, 'maybe_display_notice' ) );
function maybe_display_notice(){
$notice = get_option( 'coolmedia_role_exists_message', false );
if( $notice ){
delete_option( 'coolmedia_role_exists_message' );
$this->display_notice( $notice );
}
}
function display_notice( $notice ){
...
}https://stackoverflow.com/questions/48926053
复制相似问题