Search code examples
phpwordpresswoocommerce-subscriptionswoocommerce-memberships

Enable registration only for selective product WooCommerce


I am using WooCommerce membership for one product and the rest of the WooCommerce products are generic products.

But I want that the visitors should be able to register for WooCommerce membership but not for other products. For other products, I would like to use guest checkout.


Solution

  • There's already a solution on GitHub that you can use.

    // Code goes in theme functions.php or a custom plugin
    add_filter( 'pre_option_woocommerce_enable_guest_checkout', 'conditional_guest_checkout_based_on_product' );
    function conditional_guest_checkout_based_on_product( $value ) {
      $restrict_ids = array( 1, 2, 3 ); // Replace with product ids which cannot use guest checkout
    
      if ( WC()->cart ) {
        $cart = WC()->cart->get_cart();
        foreach ( $cart as $item ) {
          if ( in_array( $item['product_id'], $restrict_ids ) ) {
            $value = "no";
            break;
          }
        }
      }
    
      return $value;
    }