首页 > 解决方案 > 基于 WooCommerce 页面的不同消息

问题描述

我正在尝试更改将产品添加到购物车和/或通过挂接到woocommerce_add_message. 它根本没有显示任何东西,我想知道为什么。

我试过了echo,我试过return__( 了这是代码:

add_filter('woocommerce_add_message', 'change_cart_message', 10);
function change_cart_message() {

    $ncst = WC()->cart->subtotal;

    if ( is_checkout() ) {
        echo 'Your new order subtotal is: '.$ncst.'. <a style="color: green;" href="#customer_details">Ready to checkout?</a>';
    }
    elseif ( is_product() ) {
        echo 'Your new order subtotal is: '.$ncst.'. <a style="color: green;" href="'.wc_get_checkout_url().'">Ready to checkout?</a>';
    }
    else {
        echo 'Your new order subtotal is: '.$ncst.'. <a style="color: green;" href="'.wc_get_checkout_url().'">Ready to checkout?</a>';
    } 
}

我究竟做错了什么?

标签: phpwordpresswoocommercehook-woocommercenotice

解决方案


重要提示:过滤器挂钩始终有一个要返回的变量参数。

使用过滤器挂钩时,您需要始终返回过滤后的值参数(但不要回显它)......

您的代码也可以简化和压缩:

add_filter('woocommerce_add_message', 'change_cart_message', 10, 1 );
function change_cart_message( $message ) {

    $subtotal = WC()->cart->subtotal;

    $href = is_checkout() ? '#customer_details' : wc_get_checkout_url();

    return sprintf(  __("Your new order subtotal is: %s. %s"), wc_price($subtotal),
        '<a class="button alt" href="'.$href.'">' . __("Ready to checkout?") . '</a>' );
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

在此处输入图像描述


推荐阅读