Support

Account

Home Forums Front-end Issues ACF Form Unique Value Validation Reply To: ACF Form Unique Value Validation

  • Ah perfect, thanks John you are a legend! Just in case anyone in the future needs the code, here is my final code

    replaced
    'post_type' => $post_type,
    with
    'post_type' => 'inventory',
    since my CPT was inventory.

    Final code:

    add_filter('acf/validate_value/name=inventory_id', 'acf_unique_value_field', 10, 4);
    function acf_unique_value_field($valid, $value, $field, $input)
    {
        if (!$valid) {
            return $valid;
        }
        if (isset($_POST['post_ID'])) {
            $post_id = intval($_POST['post_ID']);
        } elseif (isset($_POST['post_id'])) {
            $post_id = intval($_POST['post_id']);
        } else {
            $post_id = false;
        }
        $field_name = $field['name'];
        $args = array(
            'post_type' => 'inventory',
            'post_status' => 'publish, draft, trash',
            'meta_query' => array(
                array(
                    'key' => $field_name,
                    'value' => $value
                )
            )
        );
        if (!empty($post_id)) {
            $args['post__not_in'] = array($post_id);
        }
        $query = new WP_Query($args);
        if (count($query->posts)) {
            return 'This Value is not Unique. Please enter a unique ' . $field['label'];
        }
        return true;
    }