I have a custom plugin that uses custom fields to create a post ( these custom fields will be saved as metas ).
The problem is when these custom meta values are exactly the same for another post. The task is to throw an error message and not to save the post. So far i use wp_insert_post_data to trigger my function that checks if this meta values combination already exists for antoher post.
add_filter( 'wp_insert_post_data' , 'check_duplicate_relation' , '99', 2 );
My question is: how do i stop the post from being created? I tried to return array(), return false, but the post is still created with minimal required values. I know that my function should return altered data but what i tried is to somehow trigger an error message and the post would not be created.
Any ideea how i can do this?...or what hook should i use? As far as i searched this is the one that should be used.
Thanks.
UPDATE: Here is my function: Where and what i should do?
function check_duplicate_relation($data , $postData ) {
if($data['post_type'] == 'bpp_relation' && $data['post_status'] != 'auto-draft') {
if(isset($postData['fields']) && !empty($postData['fields'])) {
$bonusProgramId = intval(array_values($postData['fields'])[0]);
$companyId = intval(array_values($postData['fields'])[1]);
if($bonusProgramId && $bonusProgramId > 1 && $companyId && $companyId > 1) {
$args = array(
'posts_per_page' => 2,
'post_type' => 'bpp_relation',
'meta_query' => array(
array(
'key' => 'company',
'value' => $companyId,
'compare' => '=',
),
array(
'key' => 'bonus_program',
'value' => $bonusProgramId,
'compare' => '=',
)
)
);
$relation = get_posts( $args );
if(empty($relation)) {
return $data;
} else {
// here the error should be returned
}
}
}
}
return $data;
}