@@ -13,18 +13,21 @@ trait WcpWooCommerceUtils
1313 * @attaches-to `woocommerce_product_set_stock` hook.
1414 *
1515 * @param \WC_Product $product A WooCommerce WC_Product object
16+ *
17+ * @return void
1618 */
1719 public function autoClearPostCacheOnWooCommerceSetStock ($ product )
1820 {
1921 $ counter = 0 ; // Initialize.
2022
2123 if (!is_null ($ done = &$ this ->cacheKey ('autoClearPostCacheOnWooCommerceSetStock ' ))) {
22- return $ counter ; // Already did this.
24+ return ; // Already did this.
2325 }
2426 $ done = true ; // Flag as having been done.
2527
2628 if (class_exists ('\\WooCommerce ' )) {
27- $ counter += $ this ->autoClearPostCache ($ product ->id );
29+ $ product_id = $ this ->getProductId ($ product );
30+ $ counter += $ this ->autoClearPostCache ($ product_id );
2831 }
2932 }
3033
@@ -36,18 +39,42 @@ public function autoClearPostCacheOnWooCommerceSetStock($product)
3639 * @attaches-to `woocommerce_product_set_stock_status` hook.
3740 *
3841 * @param string|int $product_id A WooCommerce product ID.
42+ *
43+ * @return void
3944 */
4045 public function autoClearPostCacheOnWooCommerceSetStockStatus ($ product_id )
4146 {
4247 $ counter = 0 ; // Initialize.
4348
4449 if (!is_null ($ done = &$ this ->cacheKey ('autoClearPostCacheOnWooCommerceSetStockStatus ' ))) {
45- return $ counter ; // Already did this.
50+ return ; // Already did this.
4651 }
4752 $ done = true ; // Flag as having been done.
4853
4954 if (class_exists ('\\WooCommerce ' )) {
55+ $ product_id = $ this ->getProductId ($ product_id );
5056 $ counter += $ this ->autoClearPostCache ($ product_id );
5157 }
5258 }
59+
60+ /**
61+ * Retrieve the product ID safely
62+ *
63+ * @param $product
64+ *
65+ * @return int|string
66+ */
67+ private function getProductId ($ product ) {
68+ $ id = $ product ;
69+ if (is_numeric ($ product )) {
70+ $ id = $ product ;
71+ } else if (is_object ($ product )) {
72+ if (method_exists ($ product , 'get_id ' )) {
73+ $ id = $ product ->get_id ();
74+ } else {
75+ $ id = isset ($ product ->id ) ? $ product ->id : $ product ;
76+ }
77+ }
78+ return $ id ;
79+ }
5380}
0 commit comments