Support

Account

Home Forums Front-end Issues Accept only unique values Reply To: Accept only unique values

  • Since posting that I’ve leaned some thing, like I don’t need to create a post ID field and hide it. I’ve also refined the function so that I can use the same function for any field where I want to have a unique value, just add it as a filter to any field you want to be unique.

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

    I did notice an error in your code, this:

    
    'key' => $field['type'],
    

    should be

    
    'key' => $field['name'],