使用 add_filter 自定义 WooCommerce 通知

Customizing a WooCommerce notice with add_filter

我正在尝试自定义 WooCommerce 通知。 这是我要替换的通知:

wc_add_notice( sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() ), 'error' )

基于这个有用的答案 WooCommerce Notice Messages, how do I edit them?,我想到了这个:

function my_woocommerce_membership_notice( $error ) {
    if ( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.' == $error ) {
        $error = '%s has been removed from your cart because you added a membership product. Please complete the membership purchase first.';
    }
    return $error;
}

add_filter( 'woocommerce_add_error', 'my_woocommerce_membership_notice' );

这会导致 HTTP500 错误,我无法弄清楚具体原因。

谢谢!

在网上搜索这个问题,似乎很多人在尝试使用类似的东西时都有严重的类似错误问题......

此错误消息设置在 includes/class-wc-cart.php 第 238 行。

查看 includes/wc-notice-functions.php 中的 WC 2.6 版源代码,wc_add_notice() 正在处理 2 个变量:$message$notice_type

所以这里对于 $message 变量我们有:
sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() )
而不只是:
'%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.'

%ssprintf()使用的字符串变量,被$_product->get_title()替换价值。但是你不能再在这里使用 %s 了。
这可能是您出现错误问题的原因。而不是 '%s has been… 尝试 'An item has been….

然后基于this thread,在条件中使用strpos() php函数,我编译了这个片段,没有任何保证:

function my_woocommerce_membership_notice( $message ) {
    if (strpos($message,'has been removed from your cart because it can no longer be purchased') !== false) {
        $message = 'An item has been removed from your cart because you added a membership product. Please complete the membership purchase first.';
    }
    return $message;
}
add_filter( 'woocommerce_add_error', 'my_woocommerce_membership_notice' );