问题
In Woocommerce, I would like to create a function which outputs a simple HTML table with height
, width
, regular price
and sale price
for each variation
of a variable product.
For example, let's say that the variable product comes with three variations with different dimensions and I need to make my function output this 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>
I am not sure how to build a function for this so I can add it into woocommerce_after_single_product
action inside content-single-product.php
.
How this could be done?
Any help is much appreciated.
回答1:
Update (on 2018-03-27 - Restricted to variable products only, avoiding an error)
Here is the correct way to achieve hooking it in woocommerce_after_single_product
action hook:
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;
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
All code is tested on Woocommerce 3+ and works. You can view additional hooks here…
来源:https://stackoverflow.com/questions/46342018/woocommerce-variable-products-display-some-variations-values-in-an-html-table