首页 > 解决方案 > 在购物车页面中添加自定义按钮以在购物车中添加特定产品

问题描述

尝试在购物车页面中添加自定义按钮。如果单击该按钮,则应添加特定产品,并且应使用 ajax 加载刷新购物车页面。我使用了下面的代码,但它正在刷新页面而不更新购物车价格。

        add_filter( 'woocommerce_cart_item_price', 'customizing_cart_item_name', 10, 3 );
    function customizing_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
        $product = $cart_item['data']; // Get the WC_Product Object

        if ( $value = $product->get_meta('pro_price_extra_info') ) {
            $product_name .= '<a class="gt_price" href="example.com/cart/?add-to-cart=250">Get this price</a>';
        }
        return $product_name;
    }

请帮我写代码。提前致谢

标签: wordpresswoocommercehook-woocommerce

解决方案


我刚刚测试了你的代码,它就像你提到的那样工作。您只需要添加一行来重新计算购物车总数:“WC()->cart->calculate_totals();”

根据您的代码:

add_filter( 'woocommerce_cart_item_price', 'customizing_cart_item_name', 10, 3 );
function customizing_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
    $product = $cart_item['data']; // Get the WC_Product Object

    if ( $value = $product->get_meta('pro_price_extra_info') ) {
        $product_name .= '<a class="gt_price" href="example.com/cart/?add-to-cart=250">Get this price</a>';
    }

    WC()->cart->calculate_totals();

    return $product_name;
}

为了让您的按钮获得更好的位置,您可以试试这个 ( 例子.png):

add_action( 'woocommerce_cart_collaterals', 'custom_add_to_cart_redirect' );
function custom_add_to_cart_redirect() {
      echo '<button class="de-button-admin de-button-anim-4"><a href="example.com/cart/?add-to-cart=250" style="color:white">Get Your Discounted Product!</a></button>';
}

购物车页面挂钩:https ://www.tychesoftwares.com/woocommerce-cart-page-hooks-visual-guide-with-code-examples/

我希望它有效。祝你有美好的一天。


推荐阅读