wordpressmeta-boxes

Validate MetaBox Before Inserting in The Custom Table of Database


I have a meta box to insert ISBN in the book's post type.Here is my code:

add_action('add_meta_boxes', 'book_isbn_meta_box');
function book_isbn_meta_box()
 {
   add_meta_box(
     'book_isbn_meta_box',
     'Book ISBN',
     'book_isbn_meta_box_content',
     'books',
   );
  }

function book_isbn_meta_box_content($post)
 {
   wp_nonce_field(plugin_basename(__FILE__), 'book_isbn_meta_box_content_nonce');
   ?>
    <label for="isbn"></label>
    <input type="text" id="isbn" name="isbn" placeholder="Enter ISBN" />
   <?php
 }
add_action('save_post', 'book_isbn_meta_box_save');
function book_isbn_meta_box_save($post_id)
 {
   $isbn = $_POST['isbn'];
   global $wpdb;
   $table_name = $wpdb->prefix . "books_info";
   $wpdb->insert($table_name, array('post_id' => $post_id, 'isbn' 
    => $isbn) );
 }

Now I want to validate ISBN to be unique and if it wasn't unique we shouldn't store book post type and books_info. How can I do this?


Solution

  • You can check for the existence of the isbn code by adding a pre-query before your insert. Not tested, but should work:

    function book_isbn_meta_box_save($post_id){
        $isbn = $_POST['isbn'];
        global $wpdb;
        $table_name = $wpdb->prefix . "books_info";
        
        $existing = $wpdb->get_var("SELECT post_id from $table_name WHERE isbn = $isbn;")
        if (!$existing) {
            $wpdb->insert( $table_name, array( 'post_id' => $post_id, 'isbn' => $isbn ) );
        }
    }