0
votes

On my Woocommerce shop settings I have checked the option:

[✓] Redirect to the cart page after successful addition.

And that's good behaviour for 99% of my shop.

On 1 single page (custom page with custom template) I need to enable Ajax functionality though.

Is there a way to accomplish this task in functions.php?

1
Do you want to enable AJAX add to cart based on a product ID or based on the custom template being used on the single product page?Andrew Schultz
Hi, I'd need it based on custom template (or page/url) as the same products which I need to enable ajax on are available also on other pages where ajax is not necessary..Thanks for pointing this out.Antony
So is this custom template a single product type with just the one product showing?Andrew Schultz
In my ecommerce I have 10 products available from default woocommerce pages (shop/catalog page, single product page...) which do not require ajax. Then I have the same 10 products on a custom page (inserted with [add_to_cart id="xx"] shortcodes) which do require ajax functionality instead. I hope I was clear now :)Antony
Ok thanks for the clarification now that makes sense.Andrew Schultz

1 Answers

0
votes

Ok insert this code into your functions.php. You have to replace the variable $your_ajax_page_slug with the name of your page that you want the redirect to cart functionality to be disabled. Ensure that you have 'Enable AJAX add to cart buttons on archives" checked in settings.

add_filter( 'woocommerce_get_script_data', 'modify_woocommerce_get_script_data', 20, 2 );

function modify_woocommerce_get_script_data ( $params, $handle ) {
    global $wp;

    $page_slug = '';
    $your_ajax_page_slug = 'your-page-slug';
    $current_url = home_url( $wp->request );

    // Break the URL by the delimiter
    $url_pieces = explode('/', $current_url);

    // Get the page slug
    if( is_array( $url_pieces ) )
        $page_slug = end( $url_pieces );

    if( $handle == 'wc-add-to-cart' && $page_slug == $your_ajax_page_slug ) {
        $params['cart_redirect_after_add'] = false;
    }

    return $params;
}