I have a function that take the US state list and removes states from it that we don't sell to. This works fine and removes the states from several areas, when creating an order, billing & shipping state dropdowns, etc.
Here is that function.
function wc_sell_only_states($states) {
$states_not_allowed['US'] = array(
'AL' => __('Alabama', 'woocommerce'),
'AR' => __('Arkansas', 'woocommerce'),
'MD' => __('Maryland', 'woocommerce'),
'MI' => __('Michigan', 'woocommerce'),
'MO' => __('Missouri', 'woocommerce'),
'MS' => __('Mississippi', 'woocommerce'),
'NJ' => __('New Jersey', 'woocommerce'),
'SC' => __('South Carolina', 'woocommerce'),
'TX' => __('Texas', 'woocommerce'),
'VA' => __('Virginia', 'woocommerce'),
'WV' => __('West Virginia', 'woocommerce'),
'AA' => __('Armed Forces', 'woocommerce'),
'AE' => __('Armed Forces', 'woocommerce'),
'AP' => __('Armed Forces', 'woocommerce'),
// MANUALLY ADD STATES NOT ALLOWED HERE 'STATE_ABBREVIATION' => __('State_Name', 'woocommerce'),
);
foreach ($states['US'] as $key1 => $value) {
foreach ($states_not_allowed['US'] as $key2 => $value) {
if ($key1 === $key2) {
unset($states['US'][$key1]);
}
}
}
return $states;
}
add_filter('woocommerce_states', 'wc_sell_only_states');
As you can see, when I need to make a change to the states not allowed list, I have to manually go in and add the state. To make this easier on the client, I was thinking of making an admin page that has a checkbox for all 50 states. I have the page created but not sure the of the best way to save the data and tie it back into my function.
Here I create the admin page...
function states_admin_page() {
global $allowed_states;
add_menu_page( __( 'States', 'states' ), __( 'States', 'states' ), 'edit_posts', 'add_data', 'my_states', 'dashicons-groups', 6 ) ;
}
add_action('admin_menu', 'states_admin_page');
Here is my callback function... (Not working)
function gemcore_states() {
if(!empty($_POST)) {
global $wpdb;
$table = 'states';
$data = array('selected' => $_POST['AA']);
$where = array('code' => 'AA');
$format = '%d';
$wpdb->update($table, $data, $format, $where);
if($success){
echo 'data has been save' ;
}
}else{
?>
<form method="post">
<label>Armed Forces (AA): <input type="checkbox" name="AA" /></label><br />
<!-- ... the rest of the states -->
<input type="submit" value="submit">
</form>
<?php
}
}
What is the best way to grab the checkbox values and save them to my database as 0 or 1? Then grab this data in my original function, wc_sell_only_states().
The following code will add To Woocommerce settings a submenu entry for "US states settings" page with a form containing checkboxes for all US states. Each state checked and validated will be available and allowed.
The settings data will be saved in
wp_options
table as all settings.Here is the code:
Code goes in function.php file of your active child theme (or active theme). tested and works.