custom add to cart redirection for a defined product category in WooCommerce 3

两盒软妹~` 提交于 2021-02-16 14:12:54

问题


On a WooCommerce website I would like to be redirect customers on checkout page just after a product is added to cart. However we want it to be for that specific product category instead of all the add to cart buttons.

I have tried to look up past solutions but they either just crash my site when I update the functions.php or they are outdated and don't work anymore.

I really appreciate any help.


回答1:


Updated: Add to cart redirection will not work with ajax add to cart on shop and archives pages.

You will have to choose between that 2 options for shop and archives pages:

  1. Disable ajax add-to-cart on shop and archives pages ( WC settings > Products > Display ).
  2. Add the following code to replace the add to cart button, by a button linked to the product:

This 2nd option seems to be the best:

// Replacing add to cart button link on shop and archives
add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product ) {
    if( $product->is_type( 'variable-subscription' ) || $product->is_type( 'variable' ) ) return $button;

    $button_text = __( 'View product', 'woocommerce' );
    $button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    return $button;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


THE CUSTOM CONDITIONAL REDIRECTION (For a defined product category):

Now, you can use a custom function hooked in woocommerce_add_to_cart_redirect filter hook, that will redirect customer when a product is added to cart (for a defined product category):

add_filter( 'woocommerce_add_to_cart_redirect', 'add_to_cart_checkout_redirection', 99, 1 );
function add_to_cart_checkout_redirection( $url ) {

    // HERE define your category
    $category = 'clothing';

    if ( ! isset( $_REQUEST['add-to-cart'] ) ) return $url;

    // Get the product id when it's available (on add to cart click)
    $product_id = absint( $_REQUEST['add-to-cart'] );

    // Checkout redirection url only for your defined product category
    if( has_term( $category, 'product_cat', $product_id ) ){
        // Clear add to cart notice (with the cart link).
        wc_clear_notices();
        $url = wc_get_checkout_url();
    }

    return $url;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Code is tested on Woocommerce 3+ and works



来源:https://stackoverflow.com/questions/46260883/custom-add-to-cart-redirection-for-a-defined-product-category-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!