Require a Unique Value in an ACF Field
Prevents two posts from sharing the same value in a field, such as a product code, membership number or reference ID.
Opens WPIDE on
Code
// Field that must be unique, and the post type it belongs to.
$wpide_acf_unique_field = 'reference_code';
$wpide_acf_unique_type = 'post';
add_filter( 'acf/validate_value/name=' . $wpide_acf_unique_field, function ( $valid, $value ) use ( $wpide_acf_unique_field, $wpide_acf_unique_type ) {
if ( true !== $valid || '' === trim( (string) $value ) ) {
return $valid;
}
$current = isset( $_POST['_acf_post_id'] ) ? absint( $_POST['_acf_post_id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification -- ACF verifies its own nonce.
$existing = get_posts( array(
'post_type' => $wpide_acf_unique_type,
'post_status' => array( 'publish', 'pending', 'draft', 'future', 'private' ),
'meta_key' => $wpide_acf_unique_field,
'meta_value' => sanitize_text_field( (string) $value ),
'post__not_in' => $current ? array( $current ) : array(),
'fields' => 'ids',
'posts_per_page' => 1,
'no_found_rows' => true,
) );
return $existing ? sprintf( 'This value is already used by "%s".', get_the_title( $existing[0] ) ) : $valid;
}, 10, 2 );
Notes
Set the field name and post type. The check ignores trashed posts and the post being edited.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.