在woocommerce中根据其尺寸范围(区域)设置产品价格

时间:2018-07-31 19:50:12

标签: php wordpress woocommerce area price

我将WordPress和woocommerce用于电子商务网站。 我想根据产品的面积(高度X宽度)动态计算产品

因此,产品价格将视条件而定,例如:

  • 如果区域在1 (平方呎)至5 (平方呎)之间,价格为5 $
  • 如果区域在6 (平方呎)至10 (平方呎)之间,价格为6 $

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试下面的代码示例,当产品保存在后端时,该代码示例将根据产品的区域自动计算产品价格您可能必须根据测量单位设置对面积计算进行一些调整...

代码:

add_action( 'save_post', 'calculate_product_price_based_on_area', 20, 3 );
function calculate_product_price_based_on_area( $post_id, $post, $update ) {

    if ( $post->post_type != 'product') return; // Only products

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user's permissions.
    if ( ! current_user_can( 'edit_product', $post_id ) )
        return $post_id;

    // Product width and height
    $width  = isset($_POST['_width'])  ? (float) $_POST['_width']  : 0;
    $height = isset($_POST['_height']) ? (float) $_POST['_height'] : 0;

    if( $width > 0 && $height > 0 ){
        // Area calculation from product width and height
        $area = $width * $height;

        // Define the price conditionally based on area
        if( $area > 0 && $area <= 5 ){
            $price = 5;
        } elseif( $area > 5 && $area <= 10 ){
            $price = 6;
        }

        // Update the calculated product price
        if( isset($price) && $price > 0 ){
            // if product is not on sale
            if( $_POST['_sale_price'] != '' ){
                // Update active price
                update_post_meta( $post_id, '_price', $price );
            }
            // Update regular price
            update_post_meta( $post_id, '_regular_price', $price );
            wc_delete_product_transients( $post_id ); // Update product cache
        }
    }
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试并可以正常工作。