我的WooCommerce网站是一个电子商务网站,有些产品的重量单位为“公斤”,有些产品的重量单位为“升”,有些产品的重量单位为“磅”。在 WooCommerce 中,我可以为重量选择一个独特的单位。我希望它通过输入 Like 5 Liters or 5 Kg or 5 Pounds 来手动写入一个单位。
这是屏幕截图参考:
如有任何帮助,我们将不胜感激。
可以在管理产品页面中重量字段旁边(在运输选项卡设置上)添加附加字段(单选按钮),以在产品级别管理不同的重量单位。
这是代码:
// Add custom fields to product shipping tab
add_action( 'woocommerce_product_options_dimensions', 'add_product_weight_unit_option');
function add_product_weight_unit_option(){
global $product_object;
$weight_unit = $product_object->get_meta('_weight_unit');
woocommerce_wp_radio(
array(
'id' => '_weight_unit',
'label' => __( 'Weight unit', 'woocommerce' ),
'options' => array(
'Kg' => __( 'Kg (default)', 'woocommerce' ),
'Litre' => __( 'Litre', 'woocommerce' ),
'Pound' => _x( 'Pound', 'Tax status', 'woocommerce' ),
),
'value' => $weight_unit ? $weight_unit : 'Kg',
)
);
}
// Save custom fields to product shipping tab
add_action('woocommerce_admin_process_product_object', 'save_google_meet_link_custom_field');
function save_google_meet_link_custom_field( $product ) {
if ( isset($_POST['_weight']) && ! empty($_POST['_weight']) && isset($_POST['_weight_unit']) ) {
$product->update_meta_data( '_weight_unit', esc_attr($_POST['_weight_unit']) );
}
}
// Formating weight with the weight different weight ubits
add_filter( 'woocommerce_format_weight', 'custom_format_weight', 20, 2 );
function custom_format_weight( $weight_string, $weight ){
$weight_string = wc_format_localized_decimal( $weight );
if ( ! empty( $weight_string ) ) {
$weight_label = get_post_meta( get_the_ID(), '_weight_unit', true );
$weight_string = sprintf(
_nx( '%1$s %2$s', '%1$s %2$s'.'s', $weight, 'formatted weight', 'woocommerce' ),
$weight_string,
$weight_label ? $weight_label : get_option( 'woocommerce_weight_unit' ),
);
} else {
$weight_string = __( 'N/A', 'woocommerce' );
}
return $weight_string;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。