From d833e92f05ddbf73e668f454592bf0693964a96f Mon Sep 17 00:00:00 2001 From: Karol Manijak <20098064+kmanijak@users.noreply.github.com> Date: Wed, 28 Feb 2024 10:34:37 +0100 Subject: [PATCH] Fatal error when using Product Stock Indicator or On Sale Badge blocks on a homepage (#45135) * Prevent accessing product if there's no product yet in ProductStockIndicator block * Prevent accessing product if there's no product yet in ProductSaleBadge block * Add changelog * Fix linter --- ...ck-indicator-block-within-product-collection-template | 4 ++++ .../src/Blocks/BlockTypes/ProductSaleBadge.php | 9 +++++++-- .../src/Blocks/BlockTypes/ProductStockIndicator.php | 9 +++++++-- 3 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 plugins/woocommerce/changelog/44225-product-collection-fatal-error-adding-product-stock-indicator-block-within-product-collection-template diff --git a/plugins/woocommerce/changelog/44225-product-collection-fatal-error-adding-product-stock-indicator-block-within-product-collection-template b/plugins/woocommerce/changelog/44225-product-collection-fatal-error-adding-product-stock-indicator-block-within-product-collection-template new file mode 100644 index 00000000000..a023a681f75 --- /dev/null +++ b/plugins/woocommerce/changelog/44225-product-collection-fatal-error-adding-product-stock-indicator-block-within-product-collection-template @@ -0,0 +1,4 @@ +Significance: patch +Type: fix + +Products Stock Indicator and Sale Badge: prevent fatal when block were used in a homepage diff --git a/plugins/woocommerce/src/Blocks/BlockTypes/ProductSaleBadge.php b/plugins/woocommerce/src/Blocks/BlockTypes/ProductSaleBadge.php index 1979d3c343a..1a6501221a1 100644 --- a/plugins/woocommerce/src/Blocks/BlockTypes/ProductSaleBadge.php +++ b/plugins/woocommerce/src/Blocks/BlockTypes/ProductSaleBadge.php @@ -97,8 +97,13 @@ class ProductSaleBadge extends AbstractBlock { return $content; } - $post_id = $block->context['postId']; - $product = wc_get_product( $post_id ); + $post_id = $block->context['postId']; + $product = wc_get_product( $post_id ); + + if ( ! $product ) { + return null; + } + $is_on_sale = $product->is_on_sale(); if ( ! $is_on_sale ) { diff --git a/plugins/woocommerce/src/Blocks/BlockTypes/ProductStockIndicator.php b/plugins/woocommerce/src/Blocks/BlockTypes/ProductStockIndicator.php index df7488d3de2..bc0968ea827 100644 --- a/plugins/woocommerce/src/Blocks/BlockTypes/ProductStockIndicator.php +++ b/plugins/woocommerce/src/Blocks/BlockTypes/ProductStockIndicator.php @@ -84,8 +84,13 @@ class ProductStockIndicator extends AbstractBlock { return $content; } - $post_id = $block->context['postId']; - $product = wc_get_product( $post_id ); + $post_id = $block->context['postId']; + $product = wc_get_product( $post_id ); + + if ( ! $product ) { + return ''; + } + $is_in_stock = $product->is_in_stock(); $is_on_backorder = $product->is_on_backorder();