How to Redirect specific category product pages to cart page in Woocommerce How to Redirect specific category product pages to cart page in Woocommerce wordpress wordpress

How to Redirect specific category product pages to cart page in Woocommerce


Better to use template_redirect hook. To target specific product category(ies), you can use WordPress has_term() conditional function. For cart url, is better to use WooCommerce function wc_get_cart_url()...

So in the code below define your product category(ies) term(s) name(s), slug(s) or Id(s):

add_action( 'template_redirect', 'ts_redirect_product_pages' );function ts_redirect_product_pages() {    $categories = array('my-category-1', 'my-category-2');    if ( is_product() && has_term( $categories, 'product_cat' ) ) {        wp_safe_redirect( wc_get_cart_url() );        exit;    }}

Code goes in functions.php file of the active child theme (or active theme). It should work.