Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.