0

I'm running a site that has a cookie subscription business. If a customer is already an active subscriber I'd like any additional products purchased to be half price (since they're shipped together). What is the best way to do this?

I have this function that identifies the active subscriber status:

function has_active_subscription( $user_id=null ) {
    // When a $user_id is not specified, get the current user Id
    if( null == $user_id && is_user_logged_in() ) 
        $user_id = get_current_user_id();
    // User not logged in we return false
    if( $user_id == 0 ) 
        return false;

    global $wpdb;

    // Get all active subscriptions count for a user ID
    $count_subscriptions = $wpdb->get_var( "
        SELECT count(p.ID)
        FROM {$wpdb->prefix}posts as p
        JOIN {$wpdb->prefix}postmeta as pm 
            ON p.ID = pm.post_id
        WHERE p.post_type = 'shop_subscription' 
        AND p.post_status = 'wc-active'
        AND pm.meta_key = '_customer_user' 
        AND pm.meta_value > 0
        AND pm.meta_value = '$user_id'
    " );

    return $count_subscriptions == 0 ? false : true;
}

I've tried calling a coupon code but haven't had any luck. I'm new to code.

1 Answers1

0

To implement the half-price discount for additional products purchased by active subscribers, you can use a WooCommerce filter hook to modify the product price before it's added to the cart:

add_filter( 'woocommerce_product_get_price', 'apply_half_price_for_active_subscribers', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'apply_half_price_for_active_subscribers', 10, 2 );
function apply_half_price_for_active_subscribers( $price, $product ) {
    if ( has_active_subscription() && WC()->cart->cart_contents_count > 0 ) {
        // Get the total quantity of products in the cart for the current user
        $user_id = get_current_user_id();
        $product_count = 0;
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( $cart_item['data']->get_id() != $product->get_id() && $cart_item['data']->is_purchasable() ) {
                $product_user_id = $cart_item['data']->get_meta( '_customer_user', true );
                if ( empty( $product_user_id ) || $product_user_id == $user_id ) {
                    $product_count += $cart_item['quantity'];
                }
            }
        }
        // Apply half price discount for additional products purchased
        if ( $product_count > 0 ) {
            $price = $price / 2;
        }
    }
    return $price;
}
zucc0nit
  • 346
  • 3
  • 14