Home › Forums › Front-end Issues › Accept only unique values › Reply To: Accept only unique values
Thanks John! I have no idea what I’m doing but your code got me close. I’m making a lyrics site / hymn book and want to prevent duplicate hymns, but I’m stuck. Can you get my code to validate?
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-field_key="field_581bff482f898"] {
display: none;
}
</style>
<?php
}
add_filter('acf/validate_value/type=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_581bff482f898'];
// query existing posts for matching value
$args = array(
'post_type' => 'hymn',
'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['type'],
'value' => $value
)
)
);
$query = new WP_Query($args);
if (count($query->posts)){
$valid = 'This Value is not Unique';
}
return $valid;
}
I added the hidden_post_id to the field group in the ACF menu.The hidden_post_id is working, although the acf/load_field wasn’t working for some reason.
acf/load_field gives me issues similar to these:
https://support.advancedcustomfields.com/forums/topic/acf-disappearing/
https://support.advancedcustomfields.com/forums/topic/strange-error-field-type-does-not-exist/
Lastly, while WP_Query looks like a better solution. Is there an easier way to do it with $wpdb?
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.