[英]Get shipping class name and shipping cost for product in WooCommerce
我正在嘗試在 WooCommerce 單個產品頁面上顯示產品的運輸 class 名稱和運輸統一費率。 我使用了下面的代碼:
$shipping_class_id = $product->get_shipping_class_id();
$shipping_class= $product->get_shipping_class();
$fee = 0;
if ($shipping_class_id) {
$flat_rates = get_option("woocommerce_flat_rates");
$fee = $flat_rates[$shipping_class]['cost'];
}
$flat_rate_settings = get_option("woocommerce_flat_rate_settings");
echo 'Shipping cost: ' . ($flat_rate_settings['cost_per_order'] + $fee);
我可以使用此代碼獲得運輸 class id 以及運輸 class slug,但不能獲得 label。 我也無法獲得特定運輸 class 的成本,這是運輸區域部分定義的 5 歐元統一費率。
期待您的回復。
1)獲取發貨 Class Label 名稱(來自產品):
發貨 class 已注冊為一個術語,因此您可以使用以下方式輕松獲得發貨 Class label 的產品:
$shipping_class_id = $product->get_shipping_class_id();
$shipping_class_term = get_term($shipping_class_id, 'product_shipping_class');
if( ! is_wp_error($shipping_class_term) && is_a($shipping_class_term, 'WP_Term') ) {
$shipping_class_name = $shipping_class_term->name;
}
2)運輸方式:
由於運輸方式基於客戶運輸地點,如果您有多個運輸區域,您無法真正為產品獲得您想要的特定運輸方式。
此外,根據您所有不同的運輸設置,運輸成本是從多種可能性的購物車包裹中計算出來的。
現在,如果您只有一個運輸區域,並且您想定位特定的運輸方式並獲取運輸方式標題及其大致成本(如在設置中) ,基於產品稅 class,請嘗試以下操作:
// HERE set your targeted shipping Zone type (method ID)
$targeted_shipping_method_id = 'flat_rate';
// The product shipping class ID
$product_class_id = $product->get_shipping_class_id();
$zone_ids = array_keys( array('') + WC_Shipping_Zones::get_zones() );
// Loop through Zone IDs
foreach ( $zone_ids as $zone_id ) {
// Get the shipping Zone object
$shipping_zone = new WC_Shipping_Zone($zone_id);
// Get all shipping method values for the shipping zone
$shipping_methods = $shipping_zone->get_shipping_methods( true, 'values' );
// Loop through Zone IDs
foreach ( $shipping_methods as $instance_id => $shipping_method ) {
// Shipping method rate ID
$rate_id = $shipping_method->get_rate_id();
// Shipping method ID
$method_id = explode( ':', $rate_id);
$method_id = reset($method_id);
// Targeting a specific shipping method ID
if( $method_id === $targeted_shipping_method_id ) {
// Get Shipping method title (label)
$title = $shipping_method->get_title();
$title = empty($title) ? $shipping_method->get_method_title() : $title;
// Get shipping method settings data
$data = $shipping_method->instance_settings;
## COST:
// For a defined shipping class
if( isset($product_class_id) && ! empty($product_class_id)
&& isset($data['class_cost_'.$product_class_id]) ) {
$cost = $data['class_cost_'.$product_class_id];
}
// For no defined shipping class when "no class cost" is defined
elseif( isset($product_class_id) && empty($product_class_id)
&& isset($data['no_class_cost']) && $data['no_class_cost'] > 0 ) {
$cost = $data['no_class_cost'];
}
// When there is no defined shipping class and when "no class cost" is defined
else {
$cost = $data['cost'];
}
// Testing output
echo '<p><strong>'.$title.'</strong>: '.$cost.'</p>';
}
}
}
現在,如果您想訪問運輸方式數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.