1

I'm modifying the media modal adding a new menu item to add external attachments to the media library. From the JS code I'm calling a PHP function that touches the database and accepts three parameters (url, post id and nonce). My question is, how can I check the nonce from the PHP code? Another question, is sending a nonce really necessary in this case?

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 );

}

Thanks in advance

3

As of 4.1.1, the nonce is defined in wp-includes/media.php, line 2883:

$settings['post'] = array(
    'id' => $post->ID,
    'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
);

So to verify the nonce:

wp_verify_nonce( $nonce, "update-post_$post_ID" );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.