当用户尝试通过新的WordPress Post创建新标签时,我需要显示错误。
例如:具有“编辑器”分类的用户会在WordPress中创建一个新帖子并添加一个在分类中不存在的标记我想在发布或更新时在页面顶部消除管理员错误。
这是我的代码,显示错误
function my_error_notice() {
if ( !current_user_can( 'editor' ) ) {
?>
<div class="error notice">
<p><?php _e( 'Sorry only the Administrators are allowed to create new tags, please select from the prepopulated suggestions or contact an Administrator for more assistence.', 'my_plugin_textdomain' ); ?></p>
</div>
<?php
}
add_action( 'admin_notices', 'my_error_notice' );
这是检测新标记的代码
add_action('create_term','undo_create_term',10, 3);
function undo_create_term ($term_id, $tt_id, $taxonomy) {
if ( !current_user_can( 'editor' ) ) {
if($taxonomy == 'post_tag') {
wp_delete_term($term_id,$taxonomy);
}
}
}
您必须设置瞬态变量或类似策略,因为WP在保存帖子后会执行重定向。
这是基本的想法。您需要对其进行微调才能在您的应用程序中工作:
function my_error_notice() {
$show_notice = get_transient('show_post_tag_notice');
if ( ! $show_notice ) {
return;
}
delete_transient('show_post_tag_notice');
if ( !current_user_can( 'editor' ) ) { ?>
<div class="error notice">
<p><?php _e( 'Sorry only the Administrators are allowed to create new tags, please select from the prepopulated suggestions or contact an Administrator for more assistence.', 'my_plugin_textdomain' ); ?></p>
</div>
<?php
}
}
add_action( 'admin_notices', 'my_error_notice' );
add_action('create_term','undo_create_term',10, 3);
function undo_create_term ($term_id, $tt_id, $taxonomy) {
if ( !current_user_can( 'editor' ) ) {
if($taxonomy == 'post_tag') {
wp_delete_term($term_id,$taxonomy);
set_transient('show_post_tag_notice', true);
}
}
}