Recently, we had a project using WooCommerce Memberships and needed to be able to offer a free membership subscription to first time buyers in addition to giving the membership discounted price so long as the customer is buying both. We run a check using wc_memberships_get_user_memberships( $user_id )
to check if the user has ever been a member, and then check the cart for each product using $cart_object->get_cart()
. The full code is below:
add_filter( 'woocommerce_before_calculate_totals', 'mps_registration_price', 10, 1 ); function mps_registration_price( $cart_object ) { // Bail if memberships is not active if ( ! function_exists( 'wc_memberships' ) ) return; // Exit // Only for non members $user_id = get_current_user_id(); if ( wc_memberships_get_user_memberships( $user_id ) ) return; // Exit // First loop to check if product 1 is in cart foreach ( $cart_object->get_cart() as $cart_item ){ $is_in_cart = $cart_item['product_id'] == 1 ? true : false; } // Second loop change prices foreach ( $cart_object->get_cart() as $cart_item ) { // Get an instance of the WC_Product object (or the variation product object) $product = $cart_item['data']; // Method is_on_sale() manage everything (dates…) // Here we target product ID 2 if( $product->is_on_sale() && $product->get_id() == 2 ) { // When product 1 is not cart if( ! $is_in_cart ){ $product->set_price( $product->get_sale_price() + 50); } } } }
In this example, product 1 is an item that has a special discounted price for active membership subscriptions. Product 2 is the membership subscription. If product 1 is in the cart and the user has never been a member, the price will be set to 0. If product 2 is added to the cart AND product 1 is in the cart, the price for product 2 will change to the sale price. If product 1 is removed, the price for product 2 is changed back to the original price.