# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: acf, validation, unique
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/acf-validate-unique-value/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Require a Unique Value in an ACF Field" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
