Home › Forums › Front-end Issues › Accept only unique values › Reply To: Accept only unique values
where do I put these scripts?
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;
}
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_566aa87938bba"] {
display: none;
}
</style>
<?php
}
add_filter('acf/validate_value/name=book_number', 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_566aa87938bba'];
// query existing posts for matching value
$args = array(
'post_type' => 'post',
'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['book_number'],
'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.