0

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' );
Darek Kay
  • 15,827
  • 7
  • 64
  • 61

1 Answers1

0

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.

The Humble Rat
  • 4,586
  • 6
  • 39
  • 73
  • Great, but it was not working. I still can add ISBN that already exist in database ;/ – Kamil Pilawka May 19 '15 at 13:24
  • Ołłłł yeah! I edited just this: $check = $wpdb->query( $wpdb->prepare("SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE 'cf_isbn' AND `meta_value` = ".$_POST['cf_isbn']) ); and now works correctly :D – Kamil Pilawka May 19 '15 at 13:37
  • But there is another problem- it was working only for 'xxxxxxxxxxx' values, not for 'xx-xxx-xxx'. Now I need rebuild function, or delete all "-" value in my table, but only with "meta_key = cf_isbn". Any sugestions? – Kamil Pilawka May 19 '15 at 13:49
  • Sory for spamming, but well done. by this UPDATE `wp_postmeta` SET meta_value = replace(meta_value, '-', '') WHERE meta_key LIKE 'cf_isbn' – Kamil Pilawka May 19 '15 at 14:36
  • @KamilPilawka accept the answer if it works for you. – The Humble Rat May 19 '15 at 14:40