John Davidson

php - How can I duplicate the add to cart button on the single product page, but redirect to another page?

0 comments
Message:


We're building a webshop with a lot of custom code added and hooked on WooCommerce.


On the single product page, we have ofcourse the add-to-cart button, which automatically redirects to the cart page.


Underneath the add-to-cart button, we've added a button to add the product to a 'quotation'. I general, this button has to exactly copy the Add-to-cart button functions, but in stead of redirecting to the Cart page, it has to redirect to a custom page.


There is this code to change the redirect url when adding a product in your cart, but that's not enough.


function my_custom_add_to_cart_redirect( $url ) {
$url = get_permalink( 1 ); // URL to redirect to (1 is the page ID here)
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );

When clicking on the add to cart button -> Cart page


When clicking on the add to quote button -> Custom page


Is there any possibility to 'copy' the functionalities from the Add-to-cart button, but change the redirect that's happening afterwards?


NOTE: We hooked on a few WooCommerce functions like adding Cart Item Data, so all of these have to be 'copied' as well.



My Answer:
To duplicate the add to cart button on the single product page and redirect to another page, you can create a custom button with similar functionality as the add to cart button. Here's an example of how you can achieve this:

1. Create a custom button on the single product page with the following code:

php






2. Add a function to handle the add to quote action in your theme's functions.php file:

php
function add_to_quote_action() {
if ( isset( $_POST['add_to_quote'] ) ) {
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['add_to_quote'] ) );
$product = wc_get_product( $product_id );

if ( $product ) {
$cart_item_data = array();

// Add any custom cart item data here

WC()->cart->add_to_cart( $product_id, 1, 0, $cart_item_data );

// Redirect to custom page
wp_redirect( 'http://example.com/custom-page' );
exit;
}
}
}
add_action( 'init', 'add_to_quote_action' );


3. Make sure to replace 'http://example.com/custom-page' with the URL of your custom page.

This code will add a custom button on the single product page that, when clicked, will add the product to the quote and redirect to the custom page. It also includes the functionality to add any custom cart item data if needed.

Rate this post

3 of 5 based on 1318 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us