The issue here is that the user wanted to ensure that only unique values can be entered into their custom field on their frontend form.
This means that 2 users can't have the same values in the custom fields.
Solution:
You can use the Toolset forms Validation hook to do this.
Add the following hook to your Toolset custom code section in Toolset->Custom Codes and enable it
/**
* CRED custom validation to prevent duplicates CREATE FORM
*/
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions_registration' ,10,2);
function prevent_duplicate_submissions_registration( $error_fields, $form_data) {
$nickname = $_POST['wpcf-form-field']; // Gets value from form
$unique_field = 'wpcf-field-name'; // Meta key stored in db
$form_ids = array( 69696969 ); // Edit IDs of CRED forms
list( $fields,$errors ) = $error_fields;
if ( in_array($form_data['id'], $form_ids ) ) {
// Get existing posts with unique field
$args = array(
'meta_key' => $unique_field,
'meta_value' => $nickname,
'meta_compare' => '=' ,
);
$matching = new WP_User_Query( $args );
$results = $matching->get_results();
if ( !empty( $results ) ) {
$errors[ $unique_field ] = $nickname . ' is already in use. Choose a different name.';
}
}
return array($fields,$errors);
};
/**
* CRED custom validation to prevent duplicates EDIT FORM - excludes current user from the query as it will find a matching nickname
*/
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions' ,10,2);
function prevent_duplicate_submissions( $error_fields, $form_data) {
$current_user = get_current_user_id();
$nickname = $_POST['wpcf-form-field']; // Gets value from form
$unique_field = 'wpcf-field-name'; // Meta key stored in db
$form_ids = array( 420420 ); // Edit IDs of CRED forms
list( $fields,$errors ) = $error_fields;
if ( in_array($form_data['id'], $form_ids ) ) {
// Get existing posts with unique field
$args = array(
'meta_key' => $unique_field,
'meta_value' => $nickname,
'meta_compare' => '=' ,
'exclude' => $current_user
);
$matching = new WP_User_Query( $args );
$results = $matching->get_results();
if ( !empty( $results ) ) {
$errors[ $unique_field ] = $nickname . ' is already in use. Choose a different name.';
}
}
return array($fields,$errors);
};
Note this is for a user form and will need to be customized to work for posts, however in the case of a user form you will need to change the wpcf-form-field and wpcf-field-name to the slug of the field that you want to prevent the duplicate on while keeping the wpcf- prefix on the field slug.