Site icon Hip-Hop Website Design and Development

How can I check that the acf field value is not a duplicate when adding a post?

I have a field in which I add the name of the record in the original language. And I translate the title into another language. When adding a new record, I need to check this field for duplication in other records. I did it thanks to this code, but the verification takes place only after the publication of the record.

How can I make sure that the verification is carried out in real time without publishing a record?

add_filter( 'posts_distinct', 'cf_search_distinct' );

// PREVENT POST THAT ALREADY EXIST
add_filter('acf/validate_value/name=original-title-mcpedl', 'validate_lien_video_filter', 10, 4);
add_filter('acf/load_value/name=hidden_post_id', 'add_post_id_as_value', 10, 3);
function add_post_id_as_value($value, $post_id, $field) {
  return $post_id;
}
function validate_lien_video_filter($valid, $value, $field, $input) {
    $post_id_field_key = 'field_61ab64673cad6';
  if (!$valid || $value == '' || !isset($_POST['acf'][$post_id_field_key])) {
    return $valid;
  }
    // change the field key below to the field key for your 
    // hide_post_id_field field
    $post_id = $_POST['acf'][$post_id_field_key];
  global $post; 
  $args = array(
    'post__not_in' => array($post_id), // do not check this post
    'meta_query' => array(
      array(
        'key' => 'original-title-mcpedl',
        'value' => $value
      )
    )
  );
  $query = new WP_Query($args);
  if (count($query->posts)) {
    // found at least one post that
    // already has $value
    $valid = 'This is a duplicate!';
  }
  return $valid;
}