在Woocommerce中,我想创建一个函数,为变量产品的每个height
输出一个简单的HTML表格,其中包括width
,regular price
,sale price
和variation
。
例如,假设变量产品带有三个不同尺寸的变体,我需要让我的函数输出这个HTML:
<table>
<thead>
<tr>
<th>Height</th>
<th>Width</th>
<th>Regular price</th>
<th>Sale price</th>
</tr>
</thead>
<tbody>
<tr>
<td>180cm</td>
<td>100cm</td>
<td>224€</td>
<td>176€</td>
</tr>
<tr>
<td>210cm</td>
<td>125cm</td>
<td>248€</td>
<td>200€</td>
</tr>
<tr>
<td>240cm</td>
<td>145cm</td>
<td>288€</td>
<td>226€</td>
</tr>
</tbody>
我不知道如何为此构建一个函数,所以我可以将它添加到woocommerce_after_single_product
中的content-single-product.php
动作中。
怎么做到这一点?
任何帮助深表感谢。
更新(2018-03-27 - 仅限于变量产品,避免错误)
这是在woocommerce_after_single_product
动作钩子中实现钩子的正确方法:
add_action( 'woocommerce_after_single_product', 'custom_table_after_single_product' );
function custom_table_after_single_product(){
global $product;
// Only for variable products
if( ! $product->is_type('variable')) return;
$available_variations = $product->get_available_variations();
if( count($available_variations) > 0 ){
$output = '<table>
<thead>
<tr>
<th>'. __( 'Height', 'woocommerce' ) .'</th>
<th>'. __( 'Width', 'woocommerce' ) .'</th>
<th>'. __( 'Regular price', 'woocommerce' ) .'</th>
<th>'. __( 'Sale price', 'woocommerce' ) .'</th>
</tr>
</thead>
<tbody>';
foreach( $available_variations as $variation ){
// Get an instance of the WC_Product_Variation object
$product_variation = wc_get_product($variation['variation_id']);
$sale_price = $product_variation->get_sale_price();
if( empty( $sale_price ) ) $sale_price = __( '<em>(empty)</em>', 'woocommerce' );
$output .= '
<tr>
<td>'. $product_variation->get_height() .'</td>
<td>'. $product_variation->get_width() .'</td>
<td>'. $product_variation->get_regular_price() .'</td>
<td>'. $sale_price .'</td>
</tr>';
}
$output .= '
</tbody>
</table>';
echo $output;
}
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
所有代码都在Woocommerce 3+上进行测试并且有效。你可以view additional hooks here ...