WooCommerce变量产品:在HTML表格中显示一些变体值

时间:2017-09-21 10:50:40

标签: php html wordpress woocommerce variations

在Woocommerce中,我想创建一个函数,为每个height输出一个包含widthregular pricesale pricevariation的简单HTML表格一个可变产品

例如,让我们说变量产品带有三个不同尺寸的变体,我需要让我的函数输出这个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 操作中。

如何做到这一点?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

更新 (在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 ......

enter image description here