Skip to content
Advertisement

use custome zone in woocommerce in wordpress plugin development

so this is my code

function crudStatesOperations() {
        global $wpdb;
        $country_code = 'no';

        $user_id = get_current_user_id();
        $table_name = $wpdb->prefix . 'states';
        if (isset($_POST['newsubmit'])) {
         add_filter('woocommerce_states', function ($states)  {

                $states['BB'] = array(
        'BB001' => 'St. George',
        'BB002' => 'St. Michael',
        'BB003' => 'Christ Church',
        'BB004' => 'St. Philip',
        'BB005' => 'St. Lucy',
        'BB006' => 'St. Joseph',
        'BB007' => 'St. Peter',
        'BB008' => 'St. James',
        'BB009' => 'St. Thomas',
        'BB0010' => 'St. John',
        'BB0011' => 'St. Andrew',
    );

                return $states;

            });
        }
}

and add_filter( ‘woocommerce_states’, ‘woo_custom_shipping_zones’ ); its not working inside in my function but if i put it outside and reactivate my plugin its working

how can use this filter inside the function?

Advertisement

Answer

You could use WordPress options to solve the problem:

// if the "$_POST['newsubmit']" field is set, update the "add_custom_states_woocommerce" option
function crudStatesOperations() {
    global $wpdb;
    $country_code = 'no';
    $user_id = get_current_user_id();
    $table_name = $wpdb->prefix . 'states';
    if ( isset( $_POST['newsubmit'] ) ) {
        update_option( 'add_custom_states_woocommerce', true );
    }
}

// adds custom states based on "add_custom_states_woocommerce" option
add_filter( 'woocommerce_states', 'woo_custom_shipping_zones', 10, 1 );
function woo_custom_shipping_zones( $states ) {

    if ( get_option( 'add_custom_states_woocommerce' ) ) {
        $states['BB'] = array(
            'BB001'  => 'St. George',
            'BB002'  => 'St. Michael',
            'BB003'  => 'Christ Church',
            'BB004'  => 'St. Philip',
            'BB005'  => 'St. Lucy',
            'BB006'  => 'St. Joseph',
            'BB007'  => 'St. Peter',
            'BB008'  => 'St. James',
            'BB009'  => 'St. Thomas',
            'BB0010' => 'St. John',
            'BB0011' => 'St. Andrew',
        );
    }

    return $states;

}

The code should work. Add it to your active theme’s functions.php.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement