Home › Forums › Backend Issues (wp-admin) › Restrict meta value to only be assigned once › Reply To: Restrict meta value to only be assigned once
Thanks John,
So I have got this to work now.
I created a taxonomy field and then used the validate_value filter to auto populate the field based on the existing taxonomy that had been selected for post.
I then used a tax_query combined with get_the_terms to populate the terms parameter in the tax_query based on the posts term id.
The only thing that is odd is that the validation message appears in on new page i.e. /wp-admin/post.php as opposed to being on the page.
Below is my code for reference, hopefully this helps anyone that has a similar requirement.
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;
}
//Auto populate tax field from post terms
add_filter('acf/load_value/name=topic', 'set_topic_value', 10, 3);
function set_topic_value($value, $post_id, $field) {
// Get term id for current post
$terms = get_the_terms(get_the_ID(), 'topic');
if ( $terms && !is_wp_error( $terms )) {
$term_list = wp_list_pluck( $terms, 'term_id' );
// set the value of the field to the current term id
return $term_list;
}
}
add_filter('acf/validate_value/name=top_four_num', 'require_unique', 10, 4);
function require_unique($valid, $value, $field, $input) {
// Get term id for current post
$terms = get_the_terms(get_the_ID(), 'topic');
if ( $terms && !is_wp_error( $terms )) {
$term_list = wp_list_pluck( $terms, 'term_id' );
}
if (!$valid) {
return $valid;
}
// get the post id
// using field key of post id field
$post_id = $_POST['acf']['field_57765d437d860'];
// query existing posts for matching value
$args = array(
'post_type' => 'knowledge-base',
'posts_per_page' => 1, // only need to see if there is 1
'post_status' => 'publish, draft, trash',
'post__not_in' => array($post_id),
'meta_query' => array(
array(
'key' => $field['name'],
'value' => $value
),
),
'tax_query' => array(
array(
'taxonomy' => 'topic',
'terms' => $term_list,
),
),
);
$query = new WP_Query($args);
if (count($query->posts)){
$valid = 'Value is not unqiue. Please ensure this is selected once.';
}
return $valid;
}
Thanks once again John!
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.