简体   繁体   中英

WooCommerce Redirect if user add product from a certain category to cart

I'm working on a project using woocommerce and wordpress and I need a specific feature to be implemented in it. The project requires that some products are marked as "rentals". If the user adds a product with the category of "rental", the user is redirected to a page with a contact form to be filled that will automatically contain the product's sku. The product is not to be added to the cart.

I tried use the filter "woocommerce_add_to_cart_redirect". I checked if the product belonged to a certain category and if it does, it would be redirected to the contact page. The problem was that the product was added to the cart.

add_filter( 'woocommerce_add_to_cart_redirect', 'rv_redirect_on_add_to_cart' );
function rv_redirect_on_add_to_cart() {
//Get product ID
if ( isset( $_POST['add-to-cart'] ) ) {

    $product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $_POST['add-to-cart'] );

    //Check if product ID is in the proper taxonomy and return the URL to the redirect product
    if ( has_term( 'rental', 'product_cat', $product_id ) ){
        $product = wc_get_product( $product_id );
        $_POST['rental-product-sku'] = $product->get_sku();
        return get_permalink( get_page_by_path( 'rent-a-book' ) );
    }   
}
}

So I tried to use custom validation "woocommerce_add_to_cart_validation" to check if the product belongs to the category, if it does, it returns false.

add_action( 'woocommerce_add_to_cart_validation', 'add_the_date_validation', 11, 2 ); 
function add_the_date_validation($passed, $product_id ) {
    $terms = wp_get_post_terms( $product_id, 'product_cat' );

    foreach ( $terms as $term ) $categories[] = $term->slug;
    if(count($categories) == 0){
        return true;
    }
    if ( in_array( 'rental', $categories ) ) {
        return false;
    } else {
        return true;
    }
    return true;
}

Problem is that if the validation returns false, the redirect filter isn't loaded and the user isn't redirected to the contact page. I have been researching for sometime now and I was not successful with my attempts. Can someone help me with this?

Thank you

why not do something like this?

add_action( 'woocommerce_add_to_cart_validation', 'add_the_date_validation', 11, 2 ); 
function add_the_date_validation( $passed, $product_id ) {

    if ( has_term( 'rental', 'product_cat', $product_id ) ){
        // $product = wc_get_product( $product_id );
        // $_POST['rental-product-sku'] = $product->get_sku(); 
        wp_safe_redirect(get_permalink( get_page_by_path( 'rent-a-book' ) ) );
        exit();
    }
    return $passed;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM