Home › Forums › Front-end Issues › Check for duplicate post based on custom date field › Reply To: Check for duplicate post based on custom date field
Ok, I got the wp_insert_post to work with this:
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new_event' ) {
return $post_id;
}
$start_time = $_POST['acf']['field_58c2cb3c85ad0'];
$date_key = strtotime($start_time);
$coack_key = 'coach';
$coach_object = $_POST['acf']['field_59066c838afa6']; // this works
// Create a new post
$post = array(
'post_status' => 'publish' ,
'post_type' => 'event' ,
'post_title' => 'Video Meeting',
'meta_input' => array(
'event_key' => $date_key.$coach_object
)
);
// insert the post
$post_id = wp_insert_post( $post );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post', 10, 1 );
And it works great. But I’m having trouble with the validation args. I’m not sure how to test the post value against meta input for all the events.
Here is my validation code:
function acf_unique_value_field($valid, $value, $field, $input) {
if (!$valid || (!isset($_POST['post_ID']) && !isset($_POST['post_id']))) {
return $valid;
}
if (isset($_POST['post_ID'])) {
$post_id = intval($_POST['post_ID']);
} else {
$post_id = intval($_POST['post_id']);
}
if (!$post_id) {
return $valid;
}
$post_type = get_post_type($post_id);
$field_name = $field['name'];
$args = array(
'post_type' => $post_type,
'post_status' => 'publish, draft',
'post__not_in' => array($post_id),
'meta_query' => array(
array(
'key' => $field_name,
'value' => $value
)
)
);
$query = new WP_Query($args);
if (count($query->posts)){
return 'This Value is not Unique. Please enter a unique '.$field['label'];
}
return true;
}
add_filter('acf/validate_value/name=event_key', 'acf_unique_value_field', 1, 4);
Thanks!
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.