Home › Forums › ACF PRO › 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;
}
https://support.advancedcustomfields.com/forums/topic/accept-only-unique-values/#post-45359
This solution checks the field when I click Publish Entry. And I need the field to be checked immediately after I entered the value. Before I publish the post.
Does the pre save post help?
I don’t understand, I’m not really good at programming.
I made a temporary solution until the developers tell me what to do next. The field is now being validated in the Draft. If the value is already in the database, then after saving to the draft, the field is erased.
// validate for published post (allow draft to save without validation)
if ( $post->post_status == 'draft' ) {
// bail early if validation fails
if ( ! acf_validate_save_post() ) {
return;
}
}
Edit file and the code above on 321 lines
/wp-content/plugins/advanced-custom-fields-pro/includes/forms/form-post.php
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.