Wordpress Plugin Tutorial Part VI - Using a Nonce

A nonce, according to Wikipedia, stands for "number used once", which is a technique to protect against replay attacks. You can read more on the Wikipedia article on nonce. We will change the code that we previously wrote to use a nonce so that the plugin is more secure.

First we will have to add a nonce field to the meta box area. In order to do this, we will use the wp_nonce_field function. After adding this, the 'render_ccm_meta_box_content' function will look like the following.
public function render_ccm_meta_box_content( $post )
    wp_nonce_field( plugin_basename(__FILE__),
    <label for="ccm__title_reply">
         Custom Comment Message Title : 
    <input type="text"
           value="<?php echo get_post_meta($post->ID,
                                           true); ?>"
           size="25" />
After adding this to the plugin code, if you inspect the meta-box area using Firebug or a similar software, you will see that a hidden input field is there. This is shown in the following screenshot.

Now when the post is saved this value will also be posted and can be verified in the 'ccm_save_data' function using the wp_verify_nonce function as follows.
public function ccm_save_data( $post_id )
    if ( !wp_verify_nonce( $_POST['ccm_noncename'],
                           plugin_basename(__FILE__) ) )
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
    else if ( 'post' == $_POST['post_type'] && 
            current_user_can( 'edit_page', $post_id ) )
        $ccm = $_POST['ccm_title_reply'];
        add_post_meta($post_id, 'ccm_title_reply', $ccm, true)
        update_post_meta($post_id, 'ccm_title_reply', $ccm);
Now we have successfully saved the custom comment message on a per post basis. The next step is to show this message when a post is shown to a visitor of the blog.

No comments:

Post a Comment