根据 woocommerce 中的一系列尺寸(区域)设置产品价格

Set product prices based on a range of their dimensions (area) in woocommerce

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

因此产品价格将有条件地基于区域范围,例如:

如有任何帮助,我们将不胜感激。

尝试以下代码示例,当产品保存在后端时,它会根据其面积自动计算产品价格您可能需要根据您的测量单位设置对面积计算进行一些调整...

代码:

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 文件。 已测试并有效。