WC_API_Taxes::create_tax() public WC 2.5.0
Create a tax
{} It's a method of the class: WC_API_Taxes{}
Hooks from the method
Return
Array|WP_Error.
Usage
$WC_API_Taxes = new WC_API_Taxes(); $WC_API_Taxes->create_tax( $data );
- $data(array) (required)
- -
Changelog
Since 2.5.0 | Introduced. |
Code of WC_API_Taxes::create_tax() WC API Taxes::create tax WC 5.0.0
public function create_tax( $data ) {
try {
if ( ! isset( $data['tax'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_tax_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'tax' ), 400 );
}
// Check permissions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_tax', __( 'You do not have permission to create tax rates', 'woocommerce' ), 401 );
}
$data = apply_filters( 'woocommerce_api_create_tax_data', $data['tax'], $this );
$tax_data = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '',
'tax_rate_name' => '',
'tax_rate_priority' => 1,
'tax_rate_compound' => 0,
'tax_rate_shipping' => 1,
'tax_rate_order' => 0,
'tax_rate_class' => '',
);
foreach ( $tax_data as $key => $value ) {
$new_key = str_replace( 'tax_rate_', '', $key );
$new_key = 'tax_rate' === $new_key ? 'rate' : $new_key;
if ( isset( $data[ $new_key ] ) ) {
if ( in_array( $new_key, array( 'compound', 'shipping' ) ) ) {
$tax_data[ $key ] = $data[ $new_key ] ? 1 : 0;
} else {
$tax_data[ $key ] = $data[ $new_key ];
}
}
}
// Create tax rate
$id = WC_Tax::_insert_tax_rate( $tax_data );
// Add locales
if ( ! empty( $data['postcode'] ) ) {
WC_Tax::_update_tax_rate_postcodes( $id, wc_clean( $data['postcode'] ) );
}
if ( ! empty( $data['city'] ) ) {
WC_Tax::_update_tax_rate_cities( $id, wc_clean( $data['city'] ) );
}
do_action( 'woocommerce_api_create_tax', $id, $data );
$this->server->send_status( 201 );
return $this->get_tax( $id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}