Home › Forums › Front-end Issues › Accept only unique values › Reply To: Accept only unique values
Not accepting duplicate values takes several steps.
The first thing you need to do is to have the post id available during validation. The post id is not submitted with the rest of the acf field values when it does validation so what you need to do is create a field to hold it.
After you create a field to hold the post id you need to create a load_field filter to add the post id value and make the field readonly.
add_filter('acf/load_field/name=hidden_post_id', 'make_hidden_post_id_readonly');
function make_field_readonly($field) {
// sets readonly attribute for field
$field['readonly'] = 1;
return field;
}
add_filter('acf/load_value/name=hidden_post_id', 'set_hidden_post_id_value'), 10, 3);
function set_hidden_post_id_value($value, $post_id, $field) {
// set the value of the field to the current post id
return $post_id;
}
The next thing I do is hide the field, there’s no reason to see it
add_action('admin_head', 'hide_hidden_post_id');
function hide_hidden_post_id() {
?>
<style type="text/css">
/* the field key for the post id field */
div[data-key="field_56e06fe24d3e7"] {
display: none;
}
</style>
<?php
}
Now we can validate a field so that we don’t allow duplicate values
add_filter('acf/validate_value/name=your_field_name', require_unique', 10, 4);
function require_unique($valid, $value, $field, $input) {
if (!$valid) {
return $valid;
}
// get the post id
// using field key of post id field
$post_id = $_POST['acf']['field_56e06fe24d3e7'];
// query existing posts for matching value
$args = array(
'post_type' => 'your-post-type',
'posts_per_page' = 1, // only need to see if there is 1
'post_status' => 'publish, draft, trash',
// don't include the current post
'post__not_in' => array($post_id),
'meta_query' => array(
array(
'key' => $field['name'],
'value' => $value
)
)
);
$query = new WP_Query($args);
if (count($query->posts)){
$valid = 'This Value is not Unique';
}
return $valid;
}
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.