I have single products displayed on a page with a simple query and loop.
<?php while ($wc_query->have_posts()) :
$wc_query->the_post();?>
<?php wc_get_template_part( 'content', 'single-product' ); ?>
<?php endwhile; ?>
When you hit the add to cart button the product is added to cart and the user is redirected to the single product page, but I want them to come back to the same page on which they clicked add to cart.
That was straightforward enough using
add_filter( 'woocommerce_add_to_cart_redirect', 'wp_get_referer' );
However, the user also has to enter metadata (their name for a competition entry ticket) before adding to cart. If they leave any fields blank it won't pass the add to cart validation, and in this case the user is again referred back to the single product page. Again, I want them referred back to the referring page.
This filter is in class-wc-ajax.php
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
);
which appears to be the one I need, but when I add a filter it does nothing. Even hardcoding the 'product_url' doesn't have any effect, which seems to say this code is not being run and the redirect page url is hidden somewhere else. But the filter I'm applying the validation code to is in the same add_to_cart() function as the above filter. The validation works fine, I just want it to redirect to the referring page on failure.
This question was asked before on Woocommerce redirect after add-to-cart error but although the problem was solved in a different way in the end, no-one could make that filter work.