Skip to content

Instantly share code, notes, and snippets.

@SteveJonesDev
Created October 11, 2023 18:47
Show Gist options
  • Save SteveJonesDev/f876cc49ea85b9c116c3f3b2f0bbbb16 to your computer and use it in GitHub Desktop.
Save SteveJonesDev/f876cc49ea85b9c116c3f3b2f0bbbb16 to your computer and use it in GitHub Desktop.
ACF Phone Number Validation for Custom Post Type in WordPress
<?php
/**
* Validates the 'sjd_unit_phone' field for the 'sjd_orders' custom post type.
*
* If the phone number format is incorrect, it prevents the post from being saved,
* sets the post status to 'draft', and redirects the user back to the post editor
* with a custom query parameter to indicate validation failure.
*
* @param int $post_id The ID of the post being saved.
* @return int $post_id The ID of the post being saved.
*/
function sjd_validate_sjd_unit_phone_on_save($post_id) {
// Check for the post type.
if (get_post_type($post_id) !== 'sjd_orders')
return $post_id;
// If this is just a revision or auto save, don't send back.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// If the value of our custom field isn't set, return.
if (!isset($_POST['acf']['field_64656c30bb9d8']))
return $post_id;
$phone = $_POST['acf']['field_64656c30bb9d8'];
// Check if phone format is incorrect.
if (!empty($phone) && !preg_match('/^(\(\d{3}\) \d{3}-\d{4})?$/', $phone)) {
// Remove this action to prevent an infinite loop.
remove_action('save_post', 'sjd_validate_sjd_unit_phone_on_save');
// Don't save the post.
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
// Redirect back to the edit page with a custom query var.
$location = add_query_arg('phone_validation_failed', '1', get_edit_post_link($post_id, ''));
wp_redirect($location);
exit;
}
return $post_id;
}
add_action('save_post', 'sjd_validate_sjd_unit_phone_on_save');
/**
* Displays a notice in the admin area if phone validation has failed.
*
* This function checks for the 'phone_validation_failed' query parameter
* and, if set, displays an error message to the user. This notice is only shown
* when editing the 'sjd_orders' custom post type.
*/
function sjd_display_phone_validation_notice() {
global $post_type;
// Only show the notice for the 'sjd_orders' post type.
if ($post_type === 'sjd_orders' && isset($_GET['phone_validation_failed']) && $_GET['phone_validation_failed'] == '1') {
echo '<div class="notice notice-error"><p>Please use the phone format (XXX) XXX-XXXX for the unit phone field.</p></div>';
}
}
add_action('admin_notices', 'sjd_display_phone_validation_notice');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment