在WooCommerce 3中为定义的产品类别自定义添加到购物车重定向 [英] custom add to cart redirection for a defined product category in WooCommerce 3

查看:50
本文介绍了在WooCommerce 3中为定义的产品类别自定义添加到购物车重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WooCommerce网站上,我想在产品添加到购物车后立即在结帐页面上重定向客户.但是,我们希望它是针对特定产品类别的,而不是针对所有添加到购物车"按钮的.

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.

我试图查找过去的解决方案,但是当我更新 functions.php 时,它们只是崩溃了我的网站,或者它们已经过时并且不再起作用.

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.

我非常感谢您的帮助.

推荐答案

已更新:添加到购物车"重定向不适用于在商店和档案页面上添加到购物车的ajax.

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

您将具有在商店和归档页面的这两个选项之间进行选择:

  1. 在商店和档案页面上禁用ajax添加到购物车(WC设置>产品>显示).
  2. 添加以下代码,用链接到产品的按钮替换添加到购物车"按钮:

第二个选项似乎是最好的:

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;
}

代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.

自定义条件重定向(针对已定义的产品类别):

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

现在,您可以使用连接在 woocommerce_add_to_cart_redirect 过滤器挂钩中的自定义功能,该功能将在将产品添加到购物车中时重定向客户(对于已定义的产品类别):

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;
}

代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.

代码已在Woocommerce 3+上进行了测试

Code is tested on Woocommerce 3+ and works

这篇关于在WooCommerce 3中为定义的产品类别自定义添加到购物车重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆