SAWA4D
SAWA4D

Reputation: 21

Set shipping settings programmatically in WooCommerce

I work on Wordpress plugin to administrate woocommerce via API. and i try to set the shipping cost. I can to add the area and specify the shipping method with the following code:

$new_zone_shipping  =   new WC_Shipping_Zone();
$new_zone_shipping  ->  set_zone_name("Giza");
$new_zone_shipping  ->  add_location('EG:EGGZ', 'state');
$new_zone_shipping  ->  add_shipping_method('flat_rate');
$new_zone_shipping  ->  save();

now i use for flat_rate only. Possible simple method for fixing fixed cost?

Upvotes: 1

Views: 1380

Answers (1)

SAWA4D
SAWA4D

Reputation: 21

I solved the problem after searching on WordPress databases.

The WC_Shipping_Zone method add_shipping_method() returns the shipping method instance ID .

This instance ID is grabbed in the wp_woocommerce_shipping_zones table and used in option_name column on wp_options database table like woocommerce_flat_rate_1_settings, where flat_rate is the shipping method Id (slug) and 1 is the shipping method instance Id.

So the working code is:

$zone_name     = 'Giza';
$country_state = 'EG:EGGZ';
$method_id     = 'flat_rate';
$shipping_cost = 22;

$new_zone_shipping = new WC_Shipping_Zone();
$new_zone_shipping->set_zone_name( $zone_name );
$new_zone_shipping->add_location( $country_state, 'state' );

$instance_id = $new_zone_shipping->add_shipping_method( $method_id );

$new_zone_shipping->save();

add_option( 'woocommerce_'. $method_id .'_'. $instance_id .'_settings', array(
    'title'      => $method_id,
    'tax_status' => 'taxable',
    'cost'       => $cost
),'' , 'yes' );

Important note: Don't forget to sanitize all data values as this is just a simple example.

Upvotes: 1

Related Questions