以单一价格控制多个产品价格

时间:2017-09-30 20:02:01

标签: php wordpress woocommerce hook

我正在定制wooCommerce,因此特定产品的第二个订单价格为0.00美元。我用下面的代码实现了它。

如果我是该类别的多个产品,则产品的订单会收取100美元的费用。我想将它限制在100美元。

用例将是: 每件产品都是100美元。

首次订购:客户选择多个或单个产品>收费100美元。

第二次订购:客户选择多个或单个产品>收费$ 0.

add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_cart_items_prices', 10, 1 );
function conditionally_change_cart_items_prices( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    // Set HERE the Products to check in this array
    $targeted_product_ids = array( 1107, 1113, 1115, 1116, 1117, 1118, 1119, 1121, 1122, 1123 );
    $products_bought = array();

    // Set Here your custom price (1st purshase)
    $custom_price1 = 100; // First purshase
    // Set Here your custom price (more purshases than first)
    $custom_price2 = 0; // Next purshases

    // Detecting if customer has already bought our targeted products
    if( is_user_logged_in() ){
        $customer      = wp_get_current_user();
        $customer_id   = $customer->ID; // customer ID
        $customer_email = $customer->email; // customer email

        // Checking each product in the array
        foreach( $targeted_product_ids as $product_id ){
            if( wc_customer_bought_product( $customer_email, $customer_id, $product_id) ){
                // We set all (targeted) purchased products in an array
                $products_purchased[] = $product_id;
            }
        }
    }
    // Checking cart items and changing item prices if needed
    foreach ( $cart_object->get_cart() as $cart_item ) {
        // When a targeted products already purchased is in cart we set price 2
        if ( in_array( $cart_item['product_id'], $products_purchased ) ) {
            $cart_item['data']->set_price( $custom_price2 );
        } 
        // When a targeted products is in cart and has not been purchased we set price 1
        elseif ( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
            $cart_item['data']->set_price( $custom_price1 );
        }
    }
}

0 个答案:

没有答案