我正在修改媒体模式,添加一个新的菜单项以向媒体库添加外部附件。从JS代码中,我调用了一个PHP函数,该函数涉及数据库并接受三个参数(url、post-id和nonce)。我的问题是,如何从PHP代码中检查nonce?另一个问题,在这种情况下发送nonce真的有必要吗?
JS:
wp.media.controller.Custom = wp.media.controller.State.extend({
initialize: function(){
this.props = new Backbone.Model({ url: \'\' });
},
customAction: function(){
wp.media.post( \'add-attachment\', {
url: this.props.get( \'url\' ),
post_id: wp.media.view.settings.post.id,
nonce: wp.media.view.settings.post.nonce
});
}
});
PHP:
add_action( \'wp_ajax_add-attachment\', \'add_attachment\' );
function add_attachment() {
$url = trim($_POST[\'url\']);
$post_ID = intval($_POST[\'post_id\']);
$nonce = $_POST[\'nonce\'];
CHECK NONCE HERE!
if (!current_user_can( \'edit_post\', $post_ID ) ) {
wp_send_json_error();
}
$attachment = array( ...data... );
$attachment_id = wp_insert_post( $attachment );
if( ! is_int($attachment_id) ) {
wp_send_json_error();
}
if ( ! $attachment_js = wp_prepare_attachment_for_js( $attachment_id ) ) {
wp_send_json_error();
}
wp_send_json_success( $attachment_js );
}
提前感谢
最合适的回答,由SO网友:TheDeadMedic 整理而成
自4.1.1起,nonce定义如下wp-includes/media.php
, 线2883
:
$settings[\'post\'] = array(
\'id\' => $post->ID,
\'nonce\' => wp_create_nonce( \'update-post_\' . $post->ID ),
);
因此,要验证nonce:
wp_verify_nonce( $nonce, "update-post_$post_ID" );