直接上代码,比较简单
<?php
/**
* 在文章提交框中添加“移动至回收站并通知作者”
*/
add_action( 'post_submitbox_misc_actions', 'ttzip_delete_notice_metabox' );
function ttzip_delete_notice_metabox() {
global $post;
if ( ! $post instanceof WP_Post ) {
return;
}
$nonce = wp_create_nonce( 'ttzip_delete_notice' );
?>
<div class="misc-pub-section">
<a href="javascript:void(0);"
class="submitdelete ttzip-delete-notice modown-delete-notice"
data-id="<?php echo esc_attr( $post->ID ); ?>"
data-nonce="<?php echo esc_attr( $nonce ); ?>">
移动至回收站并通知作者
</a>
</div>
<script>
jQuery(function($) {
$(document).on('click', '.ttzip-delete-notice', function(e) {
e.preventDefault();
var $link = $(this);
var ret = prompt("删除理由", "");
if ( ret === null ) {
return;
}
ret = $.trim(ret);
if ( ret === "" ) {
return;
}
$.ajax({
url: ajaxurl,
data: {
pid: $link.data("id"),
why: ret,
nonce: $link.data("nonce"),
action: "ttzip_delete_notice"
},
dataType: "json",
type: "POST",
success: function(t) {
if ( t.status == 1 ) {
location.href = "/wp-admin/edit.php";
} else {
alert(t.msg);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("请求失败,请重试");
}
});
});
});
</script>
<?php
}
add_action( 'wp_ajax_ttzip_delete_notice', 'ttzip_delete_notice_callback' );
function ttzip_delete_notice_callback() {
date_default_timezone_set( 'Asia/Shanghai' );
$status = 0;
$msg = '处理失败';
// 验证 nonce
if ( ! check_ajax_referer( 'ttzip_delete_notice', 'nonce', false ) ) {
wp_send_json( array(
'status' => $status,
'msg' => '安全校验失败'
) );
}
$post_id = isset( $_POST['pid'] ) ? absint( $_POST['pid'] ) : 0;
$why = isset( $_POST['why'] ) ? sanitize_text_field( wp_unslash( $_POST['why'] ) ) : '';
if ( ! $post_id || ! $why ) {
wp_send_json( array(
'status' => $status,
'msg' => '参数不完整'
) );
}
$cpost = get_post( $post_id );
if ( ! $cpost ) {
wp_send_json( array(
'status' => $status,
'msg' => '文章不存在'
) );
}
// 只有管理员可以操作
if ( current_user_can( 'administrator' ) ) {
// 如果 _mbt_add_notice 存在,则发送通知
if ( function_exists( '_mbt_add_notice' ) ) {
_mbt_add_notice(
$cpost->post_author,
sprintf(
__( '您好,您发表的文章《%s》审核不通过,原因:%s。', 'ttzip' ),
$cpost->post_title,
$why
),
'post_trash',
$post_id
);
}
wp_trash_post( $post_id );
$status = 1;
$msg = '已移动至回收站并通知作者';
} else {
$msg = '权限不足';
}
wp_send_json( array(
'status' => $status,
'msg' => $msg
) );
}