How to Send Passwords based on WooCommerce Product Quantity

As per our current logic, your customers will receive just one password to access your protected content, regardless of the product quantity. Actually, it would work for most use cases.

However, there comes a time when you want to generate multiple passwords based on purchased quantity.

Let’s take online training courses as an example. Trainers will buy workbooks from you, then share them with 10 different trainees. Each trainee has to have their own passwords to access their workbooks.

Instead of forcing trainers to make 10 different purchases, let’s allow them to select product quantity and get a list of 10 unique passwords at once. It would make more sense.

Requirements:

To send customers multiple passwords based on product quantity, simply add the following custom code to your (child) theme functions.php file or Code Snippets plugin.

add_filter(
	'ppwp_woo_allow_generating_passwords_with_quantity',
	function ( $allowed, $product_id, $quantity ) {
		global $ppwp_woo_password_index;
		if ( ! is_null( $ppwp_woo_password_index ) ) {
			if ( ! array_key_exists( $product_id, $ppwp_woo_password_index ) ) {
				$ppwp_woo_password_index[ $product_id ] = 0;
			}

			return true;
		}
		$ppwp_woo_password_index = [
			$product_id => 0,
		];

		add_filter(
			'ppwp_woo_product_passwords_by_quantity',
			function ( $passwords, $params ) use ( $quantity ) {
				if ( ! is_array( $passwords ) ) {
					return $passwords;
				}
				$passwords = array_values( $passwords );

				if ( count( $passwords ) >= $quantity ) {
					global $ppwp_woo_password_index;
					$index    = $ppwp_woo_password_index[ $params['product_id'] ];
					$password = $passwords[ $index ];

					$ppwp_woo_password_index[ $params['product_id'] ] = $index + 1;

					return [ $password ];
				}

				return [];
			},
			10,
			2
		);

		return true;
	},
	10,
	3
);
Lasted updated on January 20, 2022