Support

Account

Home Forums Backend Issues (wp-admin) Check if value already exist Reply To: Check if value already exist

  • @warry
    your code helps me a lot!
    it works very well when user tries to add (publish) new post with same value, it gives him the error message that I wrote, the problem happens when the user tries to update other fields at the same post and save, this gives a duplicate error (but in fact it’s not duplicated, the value is exist in only current post, not in the others)

    so, I tried to use get_the_id(); function to ignore current post ID from being checked, but it doesnt work, my code as follows, my field named as “important_estate_clients_mobile” and CPT named “important_clients”:

    // check if mobile field value is already exist
    add_filter('acf/validate_value/name=important_estate_clients_mobile', 'validate_important_clients', 10, 4);
    
    function validate_important_clients($valid, $value, $field, $input) {
      if (!$valid || $value == '') {
        return $valid;
      }
      // query posts for the same value
      // http://codex.wordpress.org/Class_Reference/WP_Query
      global $post; 
       $current_post_id = get_the_id();
      $args = array(
        'post_type' => 'important_clients',  // or your post
        'post__not_in' => array($current_post_id), // do not check this post
        'meta_query' => array(
          array(
            'key' => 'important_estate_clients_mobile',
            'value' => $value
          )
        )
      );
      $query = new WP_Query($args);
      if (count($query->posts)) {
        // found at least one post that
        // already has $value
        $valid = 'رقم العميل هذا مدخل من قبل';
      }
      return $valid;
    }