Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress Custom Meta Boxes Validation

Tags:

wordpress

Is there any way to validate custom meta box fields without using javascript. If it doesn't validate I want to stop the post from being saved to the database.

like image 237
Rakhitha Nimesh Avatar asked Oct 07 '22 00:10

Rakhitha Nimesh


1 Answers

Since the 'save_post' action is run AFTER publishing and updating, there's really no way of validating custom keys without a hackish alternative.

However, I'm thinking you can mimic the functionality you want by employing 'save_post' in the way Viral suggested, but rather than interrupt or cancel the saving process upon a validation error, you can just delete the post altogether:

add_action('save_post', 'validate_meta');
function validate_meta($post_id)
{
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
      return $post_id;
    /*USE THIS ONLY IF YOU ARE UTILIZING NONCE FIELDS IN A CUSTOM META BOX
    if ( !wp_verify_nonce( $_POST['metabox_nonce'], basename(__FILE__) ) )
      return $post_id;*/
    /*Use plugin_basename(__FILE__) if this is an actual plugin, rather than
    a part of your theme*/

    if ( 'page' == $_POST['post_type'] ) 
    {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return $post_id;
    }
    else
    {
        if ( !current_user_can( 'edit_post', $post_id ) )
            return $post_id;
    }

    /*VALIDATE YOUR METADATA HERE HOWEVER YOU LIKE
    if(is_valid($_POST['metadata']))
        $validated = true;
    else
        $validated = false;
    */

    if(!$validated)
        wp_delete_post($post_id, true);
    else
        return $post_id;
}

The only thing to watch out for with this approach is that it will run upon both Publishing and Updating as well. You may want to consider adding a check to ensure that the post is deleted only for newly published posts, and updated posts are rolled back to a previous version and the invalid revision is deleted.

like image 70
maiorano84 Avatar answered Oct 13 '22 11:10

maiorano84