Reputation: 99
We have created a landing page on our WooCommerce shop that is built with the Divi page builder.
On this landing page we have added an add-to-cart button. Now we would like to redirect this specific add-to-cart button directly to the checkout, but keep the other add-to-cart buttons on the shop and archive pages linking to the cart.
This is the code we have now in our functions.php.
First version
// get the id of the post/page based on the request uri.
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$post_id = url_to_postid($url);
// the id of the specific page/post.
$specific_post_id = 6356;
// check if the requested post id is identical to the specific post id.
if ($post_id == $specific_post_id) {
// add function to redirect the add to cart button to the checkout
add_filter('add_to_cart_redirect', 'magma_add_to_cart_redirect');
function magma_add_to_cart_redirect() {
global $woocommerce;
$magma_redirect_checkout = $woocommerce->cart->get_checkout_url();
return $magma_redirect_checkout;
}
}
Second version
add_filter('add_to_cart_redirect', 'magma_add_to_cart_redirect');
function magma_add_to_cart_redirect() {
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$post_id = url_to_postid($url);
$specific_post_id = 6356;
if ($post_id == $specific_post_id) {
global $woocommerce;
$magma_redirect_checkout = $woocommerce->cart->get_checkout_url();
return $magma_redirect_checkout;
}
}
The two parts of the code - recognizing the page & the redirect function - are working properly if they are separate from each other, for example
However, when put together, I can't seem to get it to work. Am I doing something wrong?
Help is much appreciated!
Kr, Jan
Upvotes: 0
Views: 404
Reputation: 99
For the people landing on this page and needing an answer, I found a different approach to solve this.
On the landing page - instead of using the WooCommerce add-to-cart-button from Divi - I've added the WooCommerce shortcode of an add-to-cart-button, like this
[add_to_cart id="4088" show_price="false" /]
You can find more information about WooCommerce shortcodes here: https://docs.woocommerce.com/document/woocommerce-shortcodes/
In my case, this button didn't require the price to be shown next to it (price is positioned somewhere else on the page), so I've added the value false
to the attribute show_price
.
This results in a working add-to-cart-button that adds the product with ID 4088
to the cart with AJAX.
To redirect this button to the checkout, I've added a redirect on this button set in a timeout to be triggered after 1s (after the AJAX is completed), like this.
jQuery(".ajax_add_to_cart").click( function (){
setTimeout(function() {
window.location.href = "https://xxx/nl/winkelkarretje/";
}, 1000);
});
It's probably not the most elegant solution, but it did the trick for me, so maybe it can help others too :).
Upvotes: 0