情况:Woocommerce产品对象通常包含具有原始x y z值的数组dimensions
。
$product = [
'dimensions' => [
'length' => 1,
'width' => 1,
'height' => 1
],
'dimensions_html' => '1 x 1 x 1 cm',
...
使用“Additional custom dimensions for products in Woocommerce”答案代码,我创建了3个新的自定义尺寸(深度,直径,座高)......
问题:我想将这些属性添加到产品类中,以便它们可以直接在任何地方使用,例如:
$product = [
'dimensions' => [
'length' => 1,
'width' => 1,
'height' => 1,
'depth' => 1,
'diameter' => 1,
'seat-height' => 1
],
'dimensions_html' => '1 x 1 x 1 x 1 x 1 x 1 cm',
...
如何才能做到这一点?
我工作并操纵dimensions_html
而不是包括所有必要的尺寸。这不是一个优雅或通用的解决方案,但现在对我有用。
// functions.php
add_filter( 'woocommerce_format_dimensions', 'change_formated_product_dimentions', 10, 2 );
function change_formated_product_dimentions( $dimension_string, $dimensions ){
global $product;
$cm = get_option( 'woocommerce_dimension_unit' );
$html = '';
if( $dimensions['length'] ){
$html .= '<span><strong>Length</strong> '.$dimensions['length'].' '.$cm.'</span>';
}
if( $dimensions['width'] ){
$html .= '<span><strong>Width</strong> '.$dimensions['width'].' '.$cm.'</span>';
}
if( $dimensions['height'] ){
$html .= '<span><strong>Height</strong> '.$dimensions['height'].' '.$cm.'</span>';
}
$depth = $product->get_meta( '_depth' );
if( $depth ){
$html .= '<span><strong>Depth</strong> '.$depth.' '.$cm.'</span>';
}
$diameter = $product->get_meta( '_diameter' );
if( $diameter ){
$html .= '<span><strong>Diameter</strong> '.$diameter.' '.$cm.'</span>';
}
$seat_height = $product->get_meta( '_seat_height' );
if( $seat ){
$html .= '<span><strong>Seat height</strong> '.$seat_height.' '.$cm.'</span>';
}
return $html;
}
这个现在包含在$product['dimensions_html']
中,并且当回应结果时
长度1厘米宽度1厘米高度1厘米深度1厘米直径1厘米座椅高度1厘米
(几乎)正是我想要的。