phpwordpressfieldduplication

Wordpress- prevent duplication of custom field value


I want to check values of meta-key called cf_isbn already in database in table wp-postmeta. If value is repeated, prevent insert content.

I have piece of code, that works correctly if I put xxxxxxx value to my ISBN field in frontend post-input, but the main point is change xxxxxxx with query to check values already exist in database.

Is there any php wizard who know how to help me?

function wpufe_isbn_validation( $errors ) {
    if( $_POST['cf_isbn'] == 'xxxxxxx' ) {
        $errors[] = 'this ISBN is already in database';
    }

    return $errors;
}
add_filter( 'wpuf_add_post_validation', 'wpufe_isbn_validation' );

Solution

  • You should be able to do something like so:

    function wpufe_isbn_validation( $errors )
    {
        global $wpdb;
        $check = $wpdb->query( $wpdb->prepare("
        SELECT *
        FROM wp-postmeta
        WHERE meta_key = cf_isbn AND meta_value = ".$_POST['cf_isbn']) );
    
    
        if(!empty($check))
        {
           return true;
        }
        else
        {
           return false;
        }
    }
    add_filter( 'wpuf_add_post_validation', 'wpufe_isbn_validation' );
    

    Then you can simply execute another function/piece of code depending on what is returned. Obviously if the above returns true, then the ISBN is duplicated and does not need to be inserted.