Skip to content

Instantly share code, notes, and snippets.

@mgratch
Created June 15, 2021 21:34
Show Gist options
  • Save mgratch/fd24d7c7a1476a96c806abf9bc0c8034 to your computer and use it in GitHub Desktop.
Save mgratch/fd24d7c7a1476a96c806abf9bc0c8034 to your computer and use it in GitHub Desktop.
Try to ensure billing company is unique when checking out or saving from myaccount.
<?php
/**
* Check for existing billing companies when updating my account data.
*
* @param WP_Error $errors Errors already added.
* @param stdClass $user Current User data.
*/
function wc_myaccount_validate_billing_company( $errors, $user ) {
$existing_billing_companies = wc_get_existing_billing_companies();
if ( ! empty ( $existing_billing_companies ) ) {
if ( in_array( esc_attr( stripslashes( $_POST['billing_company'] ) ), $existing_billing_companies, true ) ) {
wc_add_notice( __( '<strong>Billing Company</strong> already exists.' ), 'error' );
}
}
}
add_action( 'woocommerce_save_account_details_errors', 'wc_myaccount_validate_billing_company', 10, 2 );
/**
* Check for existing billing companies during the checkout process.
*/
function wc_checkout_validate_billing_company() {
$existing_billing_companies = wc_get_existing_billing_companies();
if ( ! empty ( $existing_billing_companies ) ) {
if ( in_array( esc_attr( stripslashes( $_POST['billing_company'] ) ), $existing_billing_companies, true ) ) {
wc_add_notice( __( '<strong>Billing Company</strong> already exists.' ), 'error' );
}
}
}
add_action( 'woocommerce_checkout_process', 'wc_checkout_validate_billing_company' );
/**
* Check the DB for existing billing company values.
*
* @return array|void
*/
function wc_get_existing_billing_companies() {
$existing_billing_companies = get_transient( 'wc_unique_billing_companies' );
if ( ! $existing_billing_companies ) {
global $wpdb;
$existing_billing_companies = $wpdb->get_results(
$wpdb->prepare(
"SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s",
'_billing_company'
),
ARRAY_A
);
if ( ! empty( $existing_billing_companies ) && is_wp_error( $existing_billing_companies ) ) {
wc_get_logger()->warning( sprintf( 'WordPress error: %s', implode( ' / ', $existing_billing_companies->get_error_messages() ) ), [] );
wc_add_notice( __( 'Something went wrong, please contact a site administrator or try again.' ), 'error' );
return;
}
set_transient( 'wc_unique_billing_companies', $existing_billing_companies );
}
return $existing_billing_companies;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment