you can use the save_post
hook to validate the uniqueness of email and phone fields before saving the post.
Replace seller
with your actual post type slug and add below code in functions.php
file
// Add custom meta box for Seller post type
function add_seller_meta_box() {
add_meta_box(
'seller_meta_box',
'Seller Details',
'render_seller_meta_box',
'seller',
'normal',
'default'
);
}
add_action('add_meta_boxes', 'add_seller_meta_box');
// Render the custom meta box fields
function render_seller_meta_box($post) {
// Add your custom fields HTML inputs here
echo '<label for="seller_email">Email:</label>';
echo '<input type="text" id="seller_email" name="seller_email" value="' . get_post_meta($post->ID, 'seller_email', true) . '" /><br>';
echo '<label for="seller_phone">Phone:</label>';
echo '<input type="text" id="seller_phone" name="seller_phone" value="' . get_post_meta($post->ID, 'seller_phone', true) . '" /><br>';
}
// Save custom meta box data
function save_seller_meta_box_data($post_id) {
// Check if it's not an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
// Check if the current user has permission to edit the post
if (!current_user_can('edit_post', $post_id)) return;
// Check if it's the correct post type
if ('seller' !== get_post_type($post_id)) return;
// Validate uniqueness of email and phone fields
$email = isset($_POST['seller_email']) ? sanitize_email($_POST['seller_email']) : '';
$phone = isset($_POST['seller_phone']) ? sanitize_text_field($_POST['seller_phone']) : '';
// Check if email or phone already exists
$existing_sellers = get_posts(array(
'post_type' => 'seller',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'seller_email',
'value' => $email,
'compare' => '='
),
array(
'key' => 'seller_phone',
'value' => $phone,
'compare' => '='
)
)
));
if (!empty($existing_sellers)) {
wp_die('A seller with this email or phone already exists.', 'Duplicate Seller', array('response' => 400));
}
// Save meta data
update_post_meta($post_id, 'seller_email', $email);
update_post_meta($post_id, 'seller_phone', $phone);
}
add_action('save_post', 'save_seller_meta_box_data');