From 02cfe23b17af870501f472f2d429328ba5f0866c Mon Sep 17 00:00:00 2001 From: Paul Kilmurray Date: Thu, 25 Jan 2024 16:24:48 +0100 Subject: [PATCH] fix: prevent POS Only products being added to cart --- includes/Products.php | 43 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/includes/Products.php b/includes/Products.php index af98062..3d33b6d 100644 --- a/includes/Products.php +++ b/includes/Products.php @@ -1,5 +1,4 @@ id = parent id. * - * @param $product + * @param WC_Product $product */ - public function product_set_stock( $product ): void { + public function product_set_stock( WC_Product $product ): void { $post_modified = current_time( 'mysql' ); $post_modified_gmt = current_time( 'mysql', 1 ); wp_update_post( @@ -61,7 +70,6 @@ public function product_set_stock( $product ): void { * Hide POS Only products from the shop and category pages. * * @TODO - this should be improved so that admin users can see the product, but get a message - * @TODO - should I use the 'woocommerce_product_query' action instead? I found it doesn't work correctly * * @param WP_Query $query Query instance. * @@ -155,6 +163,8 @@ public function filter_category_count_exclude_pos_only( $args ) { /** * Prevent POS Only products from being added to the cart. * + * NOTE: this hook is marked as deprecated. + * * @param bool $passed * @param int $product_id * @@ -162,10 +172,31 @@ public function filter_category_count_exclude_pos_only( $args ) { */ public function prevent_pos_only_add_to_cart( $passed, $product_id ) { $pos_visibility = get_post_meta( $product_id, '_pos_visibility', true ); + if ( $pos_visibility === 'pos_only' ) { return false; } return $passed; } + + /** + * Prevent POS Only products from being added to the cart via the Store API. + * + * @throws NotPurchasableException Exception if product is POS Only. + + * @param WC_Product $product Product. + * + * @return void + */ + public function store_api_prevent_pos_only_add_to_cart( WC_Product $product ) { + $pos_visibility = get_post_meta( $product->get_id(), '_pos_visibility', true ); + + if ( $pos_visibility === 'pos_only' ) { + throw new NotPurchasableException( + 'woocommerce_pos_product_not_purchasable', + $product->get_name() + ); + } + } }