Add to Cart with Options block: Prevent page redirection when clicking on Add to Cart button (https://github.com/woocommerce/woocommerce-blocks/pull/9691)

* Add isDescendentOfSingleProductBlock attribute to Add to Cart Form block

* Prevent notice from appearing when Add to Cart button is clicked

When the Add to Cart Form is added inside the Single Product Block, we
have to prevent the notice from appearing when the Add to Cart button is
clicked.

* Fix PHP CS errors

* Fix PHP CS errors

* Fix PHP CS errors

* Fix PHP CS errors

* Fix PHP CS errors

* Fix PHP CS errors

* Add phpcs:ignore WordPress.Security.NonceVerification.Recommended

* Fix Processing form data without nonce verification.

* PHP Ignore

* Improve doc comments

* Improve name for add_to_cart_message_html_filter hook

* Prevent page redirection when click on Add to Cart button

* Fix PHP CS errors
This commit is contained in:
Alexandre Lara 2023-06-05 04:50:48 -03:00 committed by GitHub
parent 37d4823680
commit 2438ce41a6
1 changed files with 23 additions and 0 deletions

View File

@ -20,11 +20,16 @@ class AddToCartForm extends AbstractBlock {
* to prevent displaying the Cart Notice when the block is inside the Single Product block
* and the Add to Cart button is clicked.
*
* It also hooks into the `woocommerce_add_to_cart_redirect` filter to prevent redirecting
* to another page when the block is inside the Single Product block and the Add to Cart button
* is clicked.
*
* @return void
*/
protected function initialize() {
parent::initialize();
add_filter( 'wc_add_to_cart_message_html', array( $this, 'add_to_cart_message_html_filter' ), 10, 2 );
add_filter( 'woocommerce_add_to_cart_redirect', array( $this, 'add_to_cart_redirect_filter' ), 10, 2 );
}
/**
@ -144,6 +149,24 @@ class AddToCartForm extends AbstractBlock {
return $message;
}
/**
* Hooks into the `woocommerce_add_to_cart_redirect` filter to prevent redirecting
* to another page when the block is inside the Single Product block and the Add to Cart button
* is clicked.
*
* @param string $url The URL to redirect to after the product is added to the cart.
* @param object $product The product being added to the cart.
* @return string The filtered redirect URL.
*/
public function add_to_cart_redirect_filter( $url, $product ) {
// phpcs:ignore
if ( isset( $_POST['is-descendent-of-single-product-block'] ) && 'true' == $_POST['is-descendent-of-single-product-block'] ) {
return wp_validate_redirect( wp_get_referer(), $url );
}
return $url;
}
/**
* Get the frontend script handle for this block type.
*